我需要一个函数,它在数据库上执行INSERT语句并返回Auto_Increment主键.我有以下C#代码但是,虽然INSERT语句工作正常(我可以看到数据库中的记录,PK是正确生成的,行== 1),但id值始终为0.任何关于可能会发生什么的想法错误?
public int ExecuteInsertStatement(string statement) { InitializeAndOpenConnection(); int id = -1; IDbCommand cmdInsert = connection.CreateCommand(); cmdInsert.CommandText = statement; int rows = cmdInsert.ExecuteNonQuery(); if (rows == 1) { IDbCommand cmdId = connection.CreateCommand(); cmdId.CommandText = "SELECT @@Identity;"; id = (int)cmdId.ExecuteScalar(); } return id; } private void InitializeAndOpenConnection() { if (connection == null) connection = OleDbProviderFactory.Instance.CreateConnection(connectString); if(connection.State != ConnectionState.Open) connection.Open(); }
为了回答答案,我试过:
public int ExecuteInsertStatement(string statement, string tableName) { InitializeAndOpenConnection(); int id = -1; IDbCommand cmdInsert = connection.CreateCommand(); cmdInsert.CommandText = statement + ";SELECT OID FROM " + tableName + " WHERE OID = SCOPE_IDENTITY();"; id = (int)cmdInsert.ExecuteScalar(); return id; }
但我现在收到错误"SQL语句结束后找到的字符"
我正在使用具有OleDb连接的MS Access数据库,Provider = Microsoft.Jet.OLEDB.4.0
1)将INSERT和SELECT语句(使用";"连接)组合成1 db命令
2)使用SCOPE_IDENTITY()代替@@ IDENTITY
INSERT INTO blabla ......; SELECT OID FROM表WHERE OID = SCOPE_IDENTITY()
- 更新:
事实证明这个问题与MS ACCESS有关,我发现这篇文章表明只需重用第一个命令并将其CommandText设置为"SELECT @@ IDENTITY"即可.
Microsoft.Jet.OLEDB.4.0提供程序支持Jet v3和Jet v4数据库引擎,但Jet v3不支持SELECT @@ IDENTITY.
MSAccess 97是Jet v3,不支持SELECT @@ IDENTITY; 它支持MSAccess 2000及更高版本.