【问题标题】:Check if existing or not in mysql database [duplicate]检查mysql数据库中是否存在[重复]
【发布时间】:2018-03-05 11:04:19
【问题描述】:

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

【问题讨论】:

  • 您正在选择整个表。如果有任何记录,则打印 Existing。这就是你想要的吗?
  • 您选择所有内容。一旦存在单个记录,该函数将返回 true。也许您尝试使用select count(*),但请注意,这在大型表上可能非常低效。最好使用insert on duplicates ignore 声明或insert .. select where not exists。这样一来,您只需往返数据库一次,并且在其他人也写入记录时出现竞争条件的风险较小。
  • 虽然我们在这里,但还值得指出的是,您的代码对 SQL 注入非常开放。而且您的变量名称只是在招致错误和意外行为。

标签: c# mysql


【解决方案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

【讨论】:

  • 我试着用你说的代码再次运行它,但它说“命令执行期间出现致命错误”我更新代码,看看。
  • 我再次更新了代码,但它不起作用。它说连接必须有效且打开,但它已经打开并且我关闭了它。
  • 它说连接必须有效并再次打开。
  • @Michelle 这就是为什么你应该总是使用using 声明。
  • conn.Open(); string sql12 = "SELECT * FROM courseandorg WHERE connID = '" + txtCOConnID.Text + "'"; 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); int count = Convert.ToInt32(cmd14.ExecuteScalar()); conn.Close();
猜你喜欢
  • 2011-12-22
  • 1970-01-01
  • 2013-05-11
  • 2012-01-26
  • 2014-09-04
  • 1970-01-01
  • 2017-11-24
  • 1970-01-01
  • 2022-11-26
相关资源
最近更新 更多