本文介绍了在SQL数据库表中插入新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的应用程序的文本框。在那些文本框输入的数据要被在数据库中插入。该CommandString中只接受字符串类型。那么,如何可以实现插入语句?
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?
string cmdString="INSERT INTO books (name,author,price) VALUES (//what to put in here?)"
我是否需要加入cmdString与textBox.Text每个值或是否有更好的选择可用?
Do I need to join the cmdString with textBox.Text for each value or is there a better alternative available?
推荐答案
使用命令
和参数
至$ P从 SQL注入$ pvent
// 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.
}
- AddWithValue
- Add (推荐方法使用的)
- AddWithValue
- Add (recommended method to use)
满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
}
}
}
这篇关于在SQL数据库表中插入新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!