如何将数据插入SQL Server

Azr*_*ria 17 c# sql sql-server

我的编码有什么问题?我无法将数据插入ms sql ..我使用C#作为前端,MS SQL作为数据库...

name = tbName.Text;
userId = tbStaffId.Text;
idDepart = int.Parse(cbDepart.SelectedValue.ToString());

string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) " +
                   " VALUES ('" + name + "', '" + userId +"', '" + idDepart + "');";

SqlCommand querySaveStaff = new SqlCommand(saveStaff);

try
{
querySaveStaff.ExecuteNonQuery();
}
catch
{
//Error when save data

MessageBox.Show("Error to save on database");
openCon.Close();
Cursor = Cursors.Arrow;
}
Run Code Online (Sandbox Code Playgroud)

ada*_*ost 32

您必须设置Command对象的Connection属性并使用参数化查询而不是硬编码SQL来避免SQL注入.

 using(SqlConnection openCon=new SqlConnection("your_connection_String"))
    {
      string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) VALUES (@staffName,@userID,@idDepartment)";

      using(SqlCommand querySaveStaff = new SqlCommand(saveStaff))
       {
         querySaveStaff.Connection=openCon;
         querySaveStaff.Parameters.Add("@staffName",SqlDbType.VarChar,30).Value=name;
         .....
         openCon.Open();

         querySaveStaff.ExecuteNonQuery();
       }
     }
Run Code Online (Sandbox Code Playgroud)

  • @ Chuki2:请注意,这个正确答案没有try/catch块,_does_有`using`块.你应该遵循这个例子. (2认同)
  • 对using子句中的连接对象不需要显式的Close() (2认同)
  • 建议使用`.AddWithValue()`. (2认同)

Joh*_*Woo 29

我认为你没有把Connection对象传递给你的command对象.它是好多了,如果你会使用commandparameters为.

using (SqlConnection connection = new SqlConnection("ConnectionStringHere"))
{
    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = connection;            // <== lacking
        command.CommandType = CommandType.Text;
        command.CommandText = "INSERT into tbl_staff (staffName, userID, idDepartment) VALUES (@staffName, @userID, @idDepart)";
        command.Parameters.AddWithValue("@staffName", name);
        command.Parameters.AddWithValue("@userID", userId);
        command.Parameters.AddWithValue("@idDepart", idDepart);

        try
        {
            connection.Open();
            int recordsAffected = command.ExecuteNonQuery();
        }
        catch(SqlException)
        {
            // error here
        }
        finally
        {
            connection.Close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为最终不是必需的,using语句的目的是即使在发生异常时也要处理连接https://msdn.microsoft.com/en-us/library/yh598w02.aspx,我错过了什么? (6认同)