我需要一个在数据库上执行 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