问题
Consider the code below:
string ConnectionString = "dsn=mysql;uid=sa;DATABASE=userdb;";
string qryStr = "insert into info(code) values(@code);";
OdbcConnection con = new OdbcConnection(ConnectionString);
OdbcCommand cmd = new OdbcCommand(qryStr,con );
cmd.Parameters.Add("@code", System.Data.Odbc.OdbcType.Int).Value = "999";
cmd.Connection.Open();
OdbcDataReader odbcdtr = cmd.ExecuteReader();//exception "must declare the scalar variable @code"
con.Close;
This code is raising exception "must declare scalar vairable @code". I'll be very grateful if anyone can point out the mistake that is in the code above.
回答1:
I've finally found the solution as given in this link.
The Odbc interface does not recognise the use of @named variables, only ? which are taken by position. You can use ?Param1, ?Param 2 for readability, but the position is all that is used.
回答2:
Try
string ConnectionString = "dsn=mysql;uid=sa;DATABASE=userdb;";
string qryStr = "insert into info(code) values(?code);";
OdbcConnection con = new OdbcConnection(ConnectionString);
OdbcCommand cmd = new OdbcCommand(qryStr,con );
cmd.Parameters.Add("@code", System.Data.Odbc.OdbcType.Int).Value = 999;
cmd.Connection.Open();
OdbcDataReader odbcdtr = cmd.ExecuteReader();
con.Close;
回答3:
Worked 100% please try this
byte[] imageDatas = ReadFile(strFn);
try
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
OdbcCommand cmd = new OdbcCommand("insert into students(id,name,img) values(" + txtId.Text + ",'" + txtName.Text + "',?)", con);
cmd.Parameters.AddWithValue("@img", imageDatas);
cmd.ExecuteNonQuery();
MessageBox.Show("inserted successfully");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
来源:https://stackoverflow.com/questions/16480827/odbc-must-declare-the-scalar-variable