gpt4 book ai didi

c# - 检查mysql数据库中是否存在

转载 作者:行者123 更新时间:2023-11-29 10:36:11 24 4
gpt4 key购买 nike

我正在尝试将数据插入 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();
}

最佳答案

您的 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相反。

关于c# - 检查mysql数据库中是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46388912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com