我正在尝试将数据插入MySQL数据库,但在此之前,我正在尝试检查该数据是否存在。如果没有,它将插入,但如果是,它将显示一条消息。 我已经运行了这段代码,但它只是说“已经存在!”即使它不存在。
try
{
conn.Open();
string sql12 = "SELECT * FROM courseandorg where connID = ?connID";
MySqlCommand cmd12 = new MySqlCommand("INSERT INTO courseandorg VALUES (connID, '" + lblCourseAbbrev.Text + "','" + lblOrgName.Text + "','" + lblOrgAbbrev.Text + "', '" + cboStatus.Text + "','" + txtquorum.Text + "')");
MySqlCommand cmd14 = new MySqlCommand(sql12, conn);
cmd14.Parameters.AddWithValue("@connID", txtCOConnID.Text);
int count = Convert.ToInt32(cmd14.ExecuteScalar());
if (count > 0)
{
MessageBox.Show("Existing!");
}
else
{
cmd12.ExecuteNonQuery();
MessageBox.Show("Successfully save!");
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
答案 0 :(得分:1)
您的select语句没有where子句,因此它会检索所有行。您应该过滤搜索,以便只检查您尝试插入的记录的现有内容:
string sql12 = "SELECT * FROM courseandorg where connID = @connID";
//Or I think in MySQL you should use ? instead of @ connID = ?connID"
cmd14.Parameters.AddWithValue("@connID",connIDValue);
此类字符串连接也为SQL injection打开。请改为parameterized queries。