如何将数据插入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; } 

您必须设置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(); } } 

我认为你没有把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(); } } } 
 string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');"; cmd = new SqlCommand(saveStaff,con); cmd.ExecuteNonQuery();