我的编码有什么问题?我无法将数据插入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;
}
答案 0 :(得分:30)
您必须设置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();
}
}
答案 1 :(得分:28)
我认为你没有将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();
}
}
}
答案 2 :(得分:-5)
string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();