【问题标题】:convert commandtext to string problem in answered question在已回答的问题中将命令文本转换为字符串问题
【发布时间】:2011-04-04 20:11:37
【问题描述】:

与此帖子相关的问题,我认为他处于离线状态,因此我无法在 atm 获得任何反馈: MySql and inserting last ID problem remains 我不确定我是否完全失明,但在这段代码中:

            // run the insert using a non query call
            command.CommandText = cmd.ToString();
            command.ExecuteNonQuery();

            /* now we want to make a second call to MYSQL to get the new index 
               value it created for the primary key.  This is called using scalar so it will
                return the value of the SQL  statement.  We convert that to an int for later use.*/
            command.CommandText = "select last_insert_id();";
            id = Convert.ToInt32(command.ExecuteScalar());

            //------- the name id does not exist in the current context

            // Commit the transaction.
            transaction.Commit();
        }
        catch (Exception ex)
        {
            Label10.Text = ": " + ex.Message;

            try
            {
                // Attempt to roll back the transaction.
                transaction.Rollback();
            }
            catch
            {
                // Do nothing here; transaction is not active.
            }
        }
    }

id 没有设置任何东西,我不确定他是如何尝试将其设置为最后插入的 id?

编辑:

int id = Convert.ToInt32(cmd.ExecuteScalar());
Label10.Text = Convert.ToString(id);

【问题讨论】:

    标签: c# asp.net mysql


    【解决方案1】:

    您应该能够使用 select @@IDENTITY; 返回插入记录的 ID,而无需使用第二个查询:

     OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('rusty@msn.com'); select @@IDENTITY;"
     int id = Convert.ToInt32(cmd.ExecuteScalar());
    

    查看您的旧问题后,这应该是相同的:

     OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('rusty@msn.com'); SELECT LAST_INSERT_ID();"
     int id = Convert.ToInt32(cmd.ExecuteScalar());
    

    【讨论】:

    • omg 这行得通我试过了,但是使用了 String.Format duhh,但现在问题出在返回的内容上,我将它设置为标签,然后返回 0?
    • 这不是它存储的内容,mysql说它会返回AI主键,它是我的用户表中的UserID?
    • ahhh 等等,不,我忘记了最后的 select 语句用 select Last insert 尝试了它,我又得到了同样的错误,所以看起来 Justin 可能是对的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多