insert into

  • Thread starter Thread starter Roy Gourgi
  • Start date Start date
R

Roy Gourgi

Hi,

How can I insert variables instead of values in the VALUES() part of the
insert into command, i.e.

var1=10;
var2=20;
var3=30

insert into emp_test (emp_no1, emp_no2, emp_no3) VALUES (var1, var2, var3)";

The above does not work.

TIA
Roy
 
Roy said:
Hi,

How can I insert variables instead of values in the VALUES() part of the
insert into command, i.e.

var1=10;
var2=20;
var3=30

insert into emp_test (emp_no1, emp_no2, emp_no3) VALUES (var1, var2, var3)";

The above does not work.

TIA
Roy

string sqlCommand = "insert into emp_test (emp_no1, emp_no2, emp_no3)";
sqlCommand += " VALUES ";
sqlCommand += "(" + var1 + ", " + var2 + ", " + var3 + ")";

if that gives you trouble (it could depending on what data is in those
variables), you should look at preparing in insert statement before you
actually execute it, then plug in variables just before you execute.

here's an example that would work with MySQL:

MySqlCommand cmd = new MySqlCommand();

cmd.CommandText = "INSERT INTO emp_test () VALUES ";
cmd.CommandText += "(?var1, ?var2, ?var3)";
cmd.Prepare();

cmd.Parameters.Add("?var1", var1);
cmd.Parameters.Add("?var2", var2);
cmd.Parameters.Add("?var3", var3);

cmd.ExecuteNonQuery();
 
insert into emp_test (emp_no1, emp_no2, emp_no3) VALUES (" + var1.ToString()
+ ", " + var2.ToString() + ", " + var3.ToString() + ")";
 
Eric said:
insert into emp_test (emp_no1, emp_no2, emp_no3) VALUES (" + var1.ToString()
+ ", " + var2.ToString() + ", " + var3.ToString() + ")";

That leaves you open to a SQL injection attack if var1, var2 or var3
are provided by the user.

Just Say No to embedding values literally into SQL - always use SQL
parameters.
 
Back
Top