我在我的申请文本框。 在这些文本框输入的数据在数据库中插入。 该CommandString中只接受字符串类型。 所以,我怎么能执行INSERT语句?
string cmdString="INSERT INTO books (name,author,price) VALUES (//what to put in here?)"
我需要与textBox.Text加入cmdString每个值,或是否有更好的选择可用?
我在我的申请文本框。 在这些文本框输入的数据在数据库中插入。 该CommandString中只接受字符串类型。 所以,我怎么能执行INSERT语句?
string cmdString="INSERT INTO books (name,author,price) VALUES (//what to put in here?)"
我需要与textBox.Text加入cmdString每个值,或是否有更好的选择可用?
使用Command
和Parameter
,从防止SQL Injection
// other codes
string cmdString="INSERT INTO books (name,author,price) VALUES (@val1, @va2, @val3)";
using (SqlCommand comm = new SqlCommand())
{
comm.CommandString = cmdString;
comm.Parameters.AddWithValue("@val1", txtbox1.Text);
comm.Parameters.AddWithValue("@val2", txtbox2.Text);
comm.Parameters.AddWithValue("@val3", txtbox3.Text);
// other codes.
}
全码:
string cmdString="INSERT INTO books (name,author,price) VALUES (@val1, @va2, @val3)";
string connString = "your connection string";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandString = cmdString;
comm.Parameters.AddWithValue("@val1", txtbox1.Text);
comm.Parameters.AddWithValue("@val2", txtbox2.Text);
comm.Parameters.AddWithValue("@val3", txtbox3.Text);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
Catch(SqlException e)
{
// do something with the exception
// don't hide it
}
}
}
你想保护自己免受SQL注入。 从字符串建立SQL是如果没有不好的做法,至少是非常可怕的。
如何:防止SQL注入在ASP.NET http://msdn.microsoft.com/en-us/library/ff648339.aspx
50种注入你的SQL http://www.youtube.com/watch?v=5pSsLnNJIa4
实体框架http://msdn.microsoft.com/en-us/data/ef.aspx