25

我的编码有什么问题?我无法将数据插入到 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;
}
4

3 回答 3

42

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

 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();
       }
     }
于 2012-09-03T01:42:06.710 回答
34

我认为你缺乏将Connection对象传递给你的command对象。command如果你会使用它会更好parameters

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();
        }
    }
}
于 2012-09-03T01:43:06.943 回答
-5
string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();
于 2013-12-24T19:18:30.140 回答