我的应用程序中有textBoxes。在这些textBox中输入的数据将插入数据库中。 commandString仅接受字符串类型。那么,我该如何实现insert语句?
string cmdString="INSERT INTO books (name,author,price) VALUES (//what to put in here?)"
我是否需要为每个值加入cmdString和textBox.Text,还是有更好的替代方案?
答案 0 :(得分:22)
使用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
}
}
}
答案 1 :(得分:1)
您希望保护自己免受SQL注入。从字符串构建sql是不错的做法,至少非常可怕。
如何:在ASP.NET中防止SQL注入 http://msdn.microsoft.com/en-us/library/ff648339.aspx
注入你的sql的50种方法 http://www.youtube.com/watch?v=5pSsLnNJIa4