【问题标题】:MySQL Insert & Select in same statement returns 'records' when none exist当不存在时,MySQL Insert & Select 在同一语句中返回“记录”
【发布时间】:2017-08-18 07:34:19
【问题描述】:

所以我有以下代码(高度简化)-

MySqlCommand CMD = new MySqlCommand(@"INSERT INTO helpdesk.calls Set CallID = @CallID, Viewed = 1, Date = current_timestamp();
SELECT * FROM helpdesk.calls WHERE ID = @CallID", Con);
CMD.Parameters.Add("CallID", MySqlDbType.Int32).Value = ID;
using (MySqlDataReader Reader = CMD.ExecuteReader()) {
    if (Reader.Read()) {
        RetVal = ToCallHeader(Reader);
    } else {
        // this never throws as Reader.Read() always returns true.
        throw new Exception(string.Format("Call ({0}) not found", ID));
    }
}

我在其中插入记录并同时运行选择。问题是,当使用插入语句时,无论是否从 select 语句中选择了任何行,Reader.Read() 都会返回 true。这是设计的行为吗?我是否需要对事务进行两个查询?

【问题讨论】:

    标签: c# mysql sql


    【解决方案1】:

    Insert Query 语法错误,会抛出异常。

    INSERT INTO helpdesk.calls Set CallID = @CallID, Viewed = 1, Date = current_timestamp();
    

    在此处检查插入语句的正确 sql 语法:https://www.w3schools.com/sql/sql_insert.asp

    【讨论】:

    • 谢谢,上面的代码被简化了,我的查询运行良好,我只是想了解为什么 reader.read 在没有结果时返回 true。
    • 您发送的实际查询是什么?如果您发送两个查询(如上),您将获得 2 个结果集。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 2019-01-25
    • 2022-01-20
    • 2016-07-02
    相关资源
    最近更新 更多