gpt4 book ai didi

c# - 将命令文本转换为已回答问题中的字符串问题

转载 作者:行者123 更新时间:2023-11-29 14:51:59 25 4
gpt4 key购买 nike

与这篇文章相关的问题,我认为他离线了,所以我无法在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);

最佳答案

您应该能够使用 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());

关于c# - 将命令文本转换为已回答问题中的字符串问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5543782/

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