मुझे एक फ़ंक्शन चाहिए जो किसी डेटाबेस पर INSERT कथन निष्पादित करता है और Auto_Increment प्राथमिक कुंजी देता है। मेरे पास निम्नलिखित सी # कोड है, लेकिन INSERT कथन ठीक काम करता है (मैं डेटाबेस में रिकॉर्ड देख सकता हूं, पीके सही ढंग से उत्पन्न होता है और पंक्तियां == 1), आईडी मान हमेशा होता है 0. क्या हो सकता है पर कोई विचार गलत?@@ 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 विवरण के अंत के बाद पाया वर्ण" त्रुटि मिल रही है ओलेडीबी कनेक्शन के साथ डेटाबेस, प्रदाता = माइक्रोसॉफ्ट.जेट.ओएलडीबी 4.0
आप क्या डेटाबेस सर्वर का उपयोग कर रहे स्पष्ट और संभवतः InitializeAndOpenConnection/connection.CreateCommand के लिए संदर्भ इनलाइन सकता है के रूप में वे करने के लिए हमारे जवाब को प्रभावित कर सकता आप? :) – Rob
इसके अलावा - "ओआईडी = SCOPE_IDENTITY()" थिंक से पूरी "चयन ओआईडी कुछ हद तक जटिल है जैसा कि आप कह रहे हैं (3 के पहचान मान के साथ रिकॉर्ड किए गए रिकॉर्ड के लिए):" table_x से 3 चुनें 3 कहां = 3 "- थोड़े अनावश्यक – Rob
@ रोब: यह अनावश्यक प्रतीत हो सकता है, लेकिन ओआईडी टाइप किया गया int है, जहां scope_identity() नहीं है, इसलिए आप सीधे (int) cmd.ExecuteScalar() – devio