我一直在努力寻找解决这个问题的方法,但到目前为止没有任何效果。
private void Insert()
{
string ConnectionStringAccess = Provider=Microsoft.ACE.OLEDB.12.0;Data Source=###Jet OLEDB:Database Password=###;
string query2 = "Select @@Identity";
int id = -1;
string Query = "INSERT INTO tblTable (EmpNo, Name) VALUES (132, 'TestName');";
OleDbConnection con = new OleDbConnection(ConnectionStringAccess);
OleDbCommand cmd = new OleDbCommand(Query, con);
try
{
con.Open();
if (cmd.ExecuteNonQuery() == 1)//the insert succeded
{
cmd.CommandText = query2;
id = Convert.ToInt32(cmd.ExecuteScalar());
}
}
catch (Exception ex)
{
//log the ex
}
finally
{
con.Dispose();
con.Close();
}
}
每次我使用上述方法时,我总是在“id”中得到 0 的返回值。我究竟做错了什么?我尝试使用不同的连接字符串或其他方式来获取最新的标识符:
- Provider=Microsoft.Jet.OLEDB.4.0;
- SCOPE_IDENTITY()
但还是没有。 Access 数据库是 2003 或更早的版本(不确定)。
最佳答案
The ms access db is 2003 or older (not sure exactly)
我能够使用 Access 97 数据库重现您的问题。 SELECT @@IDENTITY
可以正确处理 Access 2000 数据库文件(即使从与 INSERT 相同的 OleDbCommand 对象运行时也是如此),但在针对 Access 97 数据库运行时它总是返回零。
如果您想让 SELECT @@IDENTITY
正常工作,您似乎需要将数据库文件升级到更新的版本。
关于c# - Access 中的 SELECT @@IDENTITY 总是返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26868911/