Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 problem inserting variables into database

Author  Topic 

praneet83
Starting Member

2 Posts

Posted - 2006-08-31 : 10:19:43
i am working on a windows service with C# and ADO.NET

in my program logic, i get a few values stored in variables. now i want to insert these variables into a table. how do i do this?

as a simple example of what i want,


string name = "test";
string age = "100";

SqlCommand cmd =
new SqlCommand("INSERT INTO details VALUES (name,age)", conn);

conn.Open();
cmd.ExecuteNonQuery();
conn.Close();



i have the conn (connection string) and the 'details' table. but when i execute this, the values are not entered into the database..



can somebody help please...


thnx,
praneet.

harsh_athalye
Master Smack Fu Yak Hacker

5581 Posts

Posted - 2006-08-31 : 10:22:13
SqlCommand cmd =
new SqlCommand("INSERT INTO details VALUES ('" + name + "'," + age + ")", conn);

Harsh Athalye
India.
"Nothing is Impossible"
Go to Top of Page

praneet83
Starting Member

2 Posts

Posted - 2006-08-31 : 10:56:54
THANKS A LOT HARSH!
IT WORKS!!!
Go to Top of Page

KenW
Constraint Violating Yak Guru

391 Posts

Posted - 2006-08-31 : 14:35:27
Harsh,

I can't believe you didn't point out the problems with doing it like that! :-)

praneet,

You shouldn't use SQL code like that. It leaves you open for SQL injection problems.

Have a look at this: http://weblogs.sqlteam.com/jeffs/archive/2006/07/21/10728.aspx

Ken
Go to Top of Page

harsh_athalye
Master Smack Fu Yak Hacker

5581 Posts

Posted - 2006-09-01 : 04:04:59
quote:
Originally posted by KenW

Harsh,

I can't believe you didn't point out the problems with doing it like that! :-)



I don't think there is much chance of SQL Injection provided he is taking precaution to accept only valid input (no quotes, comment marks etc.) Anyway, I am a VB guy and suggested a basic technique from it, but I think, in dotNet, this can be done in better way using parameter templates.

Harsh Athalye
India.
"Nothing is Impossible"
Go to Top of Page
   

- Advertisement -