我需要一個函數,它在數據庫上執行INSERT語句並返回Auto_Increment主鍵。我有下面的C#代碼,但是,雖然INSERT語句正常工作(我可以看到數據庫中的記錄,PK生成正確,行數爲1),但id值始終爲0.關於可能發生什麼的任何想法錯誤?@@ IDENTITY INSERT語句總是返回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語句的結束後,發現」
我使用的MS Access數據庫與OleDb連接,提供程序= Microsoft.Jet.OLEDB.4.0
你能澄清你正在使用的數據庫服務器,並可能對內嵌InitializeAndOpenConnection/connection.CreateCommand引用,因爲它們可能會影響我們的答案您? :) – Rob 2008-10-09 10:00:54
此外 - 整個「選擇OID從x其中OID = SCOPE_IDENTITY()」瘦有點過於複雜,你說的(對於插入身份值爲3的記錄):「SELECT 3 FROM table_x WHERE 3 = 3「 - 有點多餘 – Rob 2008-10-09 10:02:21
@Rob:它可能看起來多餘,但OID是鍵入int,其中scope_identity()不是,所以你可以直接拋出(int)cmd.ExecuteScalar() – devio 2008-10-09 13:03:50