开发者

insert query syntax problem

开发者 https://www.devze.com 2023-01-22 13:57 出处:网络
i have a SQL query as follows String S = Editor1.Content.ToString(); Response.Write(S); string sql = \"insert into testcase.ishan(nmae,orders) VALUES (\'9\',@S)\";

i have a SQL query as follows

  String S = Editor1.Content.ToString();
     Response.Write(S);   
    string sql = "insert into testcase.ishan(nmae,orders) VALUES ('9',@S)";
   OdbcCommand cmd开发者_如何学C = new OdbcCommand(sql, myConn);
            cmd.Parameters.AddWithValue("@S", S); 
            cmd.ExecuteNonQuery();

Error: Column 'orders' cannot be null at System.Data.Odbc.OdbcConnection.HandleError


Better to use something like:

var sqlCommandText = "insert into testcase.ishan(nmae,orders) VALUES ('9', @S)";
using (var connection = new SqlConnection())
{
    using (var command = new SqlCommand(sqlCommandText , connection))
    {
        command.Parameters.AddWithValue("@S", S);
        command.ExecuteNonQuery();
    }
}

The use of parameters prevents SQL injection. Andrews solution does not, I believe.

ExecuteNonQuery() will return the number of rows affected, if you need it.

The using statements will take care of disposing the connection properly, so afterwards, you have no open connections anymore. This is because SqlConnection implements IDisposable.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号