Insert data into SQL Server from C# code

前端 未结 7 1933
自闭症患者
自闭症患者 2021-01-06 06:59

I have a table student (id, name). Then I have one textbox, for entering the name, when click on submit button, it inserts the data into the databa

7条回答
  •  忘掉有多难
    2021-01-06 07:05

    You better use parameters when you insert data.

    try
    {
        string sql = "insert into student(name) values (@name)";
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                cmd.Parameters.AddWithValue("@name", test); // assign value to parameter 
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (SqlException ex)
    {
        string msg = "Insert Error:";
        msg += ex.Message;
    }
    

提交回复
热议问题