如何使用c#按钮单击将数据添加到mysql数据库表中的指定列中,一旦我单击按钮,它将传递给catch
这是我的添加按钮代码
private void Button_add_Click(object sender, RoutedEventArgs e)
{
try
{
string Query = @"INSERT INTO `bcasdb`.`tbl_department`(
`dep_id`,
`dep_name`,
`tbl_branch_branch_id`)
VALUES ("
+ this.depIDInput.Text + ",'"
+ this.depnameInput.Text + "','"
+ this.dep_branchIDInput.Text + "')";
//This is command class which will handle the query and connection object.
MySqlConnection conn = new MySqlConnection(BCASApp.DataModel.DB_CON.connection);
MySqlCommand cmd = new MySqlCommand(Query, conn);
MySqlDataReader MyReader;
conn.Open();
MyReader = cmd.ExecuteReader();// Here our query will be executed and data saved into the database.
conn.Close();
successmsgBox();
}
catch (Exception)
{
errormsgBox();
}
}
这是表格的所有列,
INSERT INTO `bcasdb`.`tbl_student`
(`reg_id`,
`std_fname`,
`std_lname`,
`tbl_batch_batch_id`,
`gender`,
`dob`,
`email`,
`mobile`,
`contact_address`,
`home_address`,
`status`,
`course_id`,
`depart_id`,
`parent_name`,
`telephone`,
`nationality`,
`nic`,
`passport_no`,
`acadamic_qulification`,
`current_employement`,
`gce_ol`,
`gce_al`,
`birth_certifiacte`,
`copy_of_nic`,
`police_clerence`,
`tbl_studentcol`)
VALUES
最佳答案
我相信您的代码应该重写如下:
private void Button_add_Click(object sender, RoutedEventArgs e)
{
try
{
string Query = @"INSERT INTO `bcasdb`.`tbl_department`(
`dep_id`,
`dep_name`,
`tbl_branch_branch_id`)
VALUES (@depId, @depName, @branchId)";
//This is command class which will handle the query and connection object.
using (MySqlConnection conn = new MySqlConnection(BCASApp.DataModel.DB_CON.connection))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(Query, conn))
{
cmd.Parameters.Add("@depId", this.depIDInput.Text);
cmd.Parameters.Add("@dep_name", this.depnameInput.Text);
cmd.Parameters.Add("@branchId", this.dep_branchIDInput.Text);
cmd.ExecuteNonQuery();
}
}
successmsgBox();
}
catch (Exception)
{
errormsgBox();
}
}
关于c# - 如何使用c#将数据添加到mysql中的指定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26271234/