在SQL数据库表中插入新行数据库、SQL

2023-09-04 02:18:24 作者:祭司大人

我在我的应用程序的文本框。在那些文本框输入的数据要被在数据库中插入。该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
        }
    }
}