Insert sql string

  • Thread starter Thread starter firebalrog
  • Start date Start date
F

firebalrog

This is pretty close. You may also be able to do cn.Execute sqlstring.
System.Data.SqlClient.SqlConnection cn = new
System.Data.SqlClient.SqlConnection(....);
cn.Open();;
System.Data.SqlClient.SqlCommand cmd=new
System.Data.SqlClient.SqlCommand(cn);
cmd.CommandText= "insert into fred (a,b) values (1,'a')";
cmd.ExecuteNonScalar();
cn.Close();
 
How can I make a insert sql string to insert direct in a table(not a
dataset) using the textbox.text propert??
 
Ok, thx, but if I want to insert the text of a textbox, will this
works???


cmd.CommandText= "insert into fred (name) values
("+txtName.Text.ToString()+")";


Am I right???
 
Ah yes ... he didn't really answer your original question explicitly, did
he? Although he gave you enough to put it together pretty easily.

Here's his insert:

cmd.CommandText= "insert into fred (a,b) values (1,'a')";

Now, if you want to put the value of a textbox into field b in his example,
you would replace the value 'a' with the textbox value. That would be the
Text property of the textbox, so if the texbox were named myTextBox, you'd
have:

cmd.CommandText = String.Format("insert into fred (a,b)
values(1,'{0}')",myTextBox.Text);

Of course this is static SQL which is inefficient and sets you up for SQL
injection attacks and would also blow up if for example the user happened to
type an apostrophe into the textbox, so what you would really want to do is
a parameterized query. So his original code would be something like this:

System.Data.SqlClient.SqlConnection cn = new
System.Data.SqlClient.SqlConnection(....);
cn.Open();;
System.Data.SqlClient.SqlCommand cmd=new
System.Data.SqlClient.SqlCommand(cn);
cmd.CommandText= "insert into fred (a,b) values (@a,@b)";
cmd.Parameters.Add("@a",SqlDbType.Int).Value = 1;
cmd.Parameters.Add("@b",SqlDbType.Varchar,20).Value = myTextBox.Text;
cmd.ExecuteNonQuery();
cn.Close();

Ignoring, of course, validation in the textbox, error handling, the exact
schema of your database, etc. But this should give you the basic direction.

--Bob
 
Ricardo Luceac said:
Ok, thx, but if I want to insert the text of a textbox, will this
works???


cmd.CommandText= "insert into fred (name) values
("+txtName.Text.ToString()+")";

Am I right???

Well, that will work in some situations. In others, it could do
horrible things to your database, if people put dodgy things into the
text box. You should use command parameters.

See http://www.pobox.com/~skeet/csharp/faq/#db.parameters
 
Thx, i already made it work, but this way you show seens to be much
better... thanks...
 
Back
Top