我的应用程序中有文本框。在那些文本框中输入的数据将被插入数据库中。commandString仅接受字符串类型。那么,如何实现插入语句?
string cmdString="INSERT INTO books (name,author,price) VALUES (//what to put in here?)"
我是否需要将cmdString与textBox.Text的每个值连接在一起,或者有更好的替代方法吗?
使用Command并Parameter防止SQL Injection
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 } } }