What the problem on my coding? I cannot insert data to ms sql.. I'm using C# as front end and MS SQL as databases.
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;
}
Answer:
You have to set Connection property of Command object and use parametersized query instead of hardcoded SQL to avoid 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.AddWithValue("@staffName",name);
querySaveStaff.Parameters.AddWithValue("@userID",userId);
querySaveStaff.Parameters.AddWithValue("@idDepartment",idDepart);
openCon.Open();
int temp= cmd.ExecuteNonQuery();
if(temp>0)
{
lblmsg.Text=”Save…”;
}
else
{
lblmsg.Text=”No Save…”;
}
}
}
No comments:
Post a Comment