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;
}
This question is related to
c#
sql
sql-server
I think you lack to pass Connection
object to your command
object. and it is much better if you will use command
and parameters
for that.
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();
Source: Stackoverflow.com