C# 在sql数据库表中插入新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14001040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inserting new row in sql database table
提问by Victor Mukherjee
I have textBoxes in my application. The data entered in those textBoxes are to be inserted in the database. The commandString accepts string type only. So, how can I implement the insert statement?
我的应用程序中有文本框。在这些文本框中输入的数据将被插入到数据库中。commandString 只接受字符串类型。那么,如何实现插入语句呢?
string cmdString="INSERT INTO books (name,author,price) VALUES (//what to put in here?)"
Do I need to join the cmdString with textBox.Text for each value or is there a better alternative available?
对于每个值,我是否需要将 cmdString 与 textBox.Text 连接起来,还是有更好的替代方法?
采纳答案by John Woo
use Command
and Parameter
to prevent from 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.
}
full code:
完整代码:
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
}
}
}
回答by Michael Viktor Starberg
You want to protect yourself from SQL Injection. Building up sql from strings is if not bad practice, at least very scary.
您想保护自己免受 SQL 注入。从字符串构建 sql 是一种不好的做法,至少非常可怕。
How To: Protect From SQL Injection in ASP.NET http://msdn.microsoft.com/en-us/library/ff648339.aspx
如何:防止 ASP.NET 中的 SQL 注入 http://msdn.microsoft.com/en-us/library/ff648339.aspx
50 ways to inject your sql http://www.youtube.com/watch?v=5pSsLnNJIa4
注入 sql 的 50 种方法 http://www.youtube.com/watch?v=5pSsLnNJIa4
Entity Framework http://msdn.microsoft.com/en-us/data/ef.aspx