我正在尝试向MySQL数据库插入一个数据,但在此之前,我正在尝试检查该数据是否存在。如果不是,它将插入,但如果是,它将显示一条消息。我运行过这段代码,但它只显示"Existing!“即使它并不存在。
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();
}发布于 2017-09-24 18:15:43
您的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。
https://stackoverflow.com/questions/46388912
复制相似问题