2013-03-18 5 views
6

WP8 के साथ SQLite मुझे पागल कर रहा है। :(WP8/C#/SQLite: अंतिम डाली गई आईडी प्राप्त करें?

सभी मैं करना चाहता हूँ पिछले डाला आईडी का मान प्राप्त करने के लिए है ...

मुझे मिल गया है:

class ShoppingItem 
{ 
    [SQLite.PrimaryKey, SQLite.AutoIncrement] 
    public int Id {get; set;} 
    public string Name {get; set;} 
    public string Shop {get; set;} 
    public bool isActive {get; set;} 
} 

ठीक है, न SQLiteConnection वस्तु का इस्तेमाल किया है और न ही इसकी Table<ShoppingItem> एक उचित सदस्य है कि पिछले आईडी है शामिल करने के लिए लग रहे हैं

तो मैं करने की कोशिश की:।

private int GetLastInsertedRowID() 
{ 
    int Result = -1; 
    using (var db = new SQLiteConnection(m_DatabasePath)) { 
    Result = db.ExecuteScalar<int>("SELECT last_insert_rowid();"); 
    } 
    return Result; 
} 

लेकिन यह फ़ंक्शन हमेशा 0 देता है। :( लेकिन जब मैं ShoppingItem के सभी प्रविष्टियों को पढ़ने, उनकी आईडी मान = 0.

तो मेरे सवाल है: मैं पिछले डाला आईडी कैसे पुनर्प्राप्त कर सकते हैं

पुनश्च:? SQL क्वेरी बदलने के लिए SELECT last_insert_rowid() FROM ShoppingItem; एक ही परिणाम दे दी है

पी पी एस:। Getting the Last Insert ID with SQLite.NET in C# तरह समाधान संकलन नहीं है, जाहिरा तौर पर वहाँ एक पूरी तरह से अलग एपीआई

+0

db.ExecuteScalar है ("का चयन करें last_insert_rowid()"); काम कर रहे? (बिना; क्वेरी के अंत में) – Joel

+0

नहीं, उसी परिणाम के साथ या बिना अर्धविराम :( –

+0

मैं अनुशंसा करता हूं कि आप अपने पीके कॉलम 'आईडी' के लिए एक अलग नाम चुनें। मुझे नहीं पता कि आईडी कुछ ऐसा है या नहीं आंतरिक कीवर्ड। लेकिन मैं बस अनुमान लगा रहा हूं। – Joel

उत्तर

11

क्योंकि आप इसे एक अलग डेटाबेस कनेक्शन में चल रहे हैं आपका SELECT last_insert_rowid() कॉल काम नहीं करता।

वैसे भी, तुम सिर्फ डाला ShoppingItem वस्तु से आईडी पढ़ना चाहिए, इस तरह:

var si = new ShoppingItem() { 
    Name = anItem, 
    Shop = aShop, 
    isActive = aIsActive, 
}; 
db.Insert(si); 
return si.Id; 
+0

आह, ठीक है, नया कनेक्शन प्रोब है। लेकिन मैं ऑब्जेक्ट से आईडी कैसे पढ़ूं, जिसे मैंने अभी डाला है? –

+0

मेरे अपडेट किए गए समाधान (विधि: insertExpenseItem2) पर एक नज़र डालें। क्वेरी एक लेनदेन में encapsulated है और इसलिए एक ही डेटाबेस कनेक्शन का उपयोग करता है। – Joel

+0

बहुत बहुत धन्यवाद। दुर्भाग्य से मुझे "नया" SQLite का कोई अच्छा दस्तावेज नहीं मिला। –

0

इस के साथ एक पुराने संस्करण का इस्तेमाल किया SQLite है, क्या मैं पिछले डाला आइटम की आईडी को पुनः प्राप्त करने के लिए क्या है प्रदान किया गया कोड स्निपेट मेरे वाई में काम करता है SQLite 3.7.XX (SQLite) का उपयोग कर ndows 8 ऐप।

public class ExpenseDataMapper 
    { 
     SQLiteConnection connection; 

     /// <summary> 
     /// Constructor 
     /// </summary> 
     public ExpenseDataMapper() 
     { 
      connection = new SQLiteConnection(StaticResources.DATABASE_PATH_NAME); 

      connection.CreateTable<FinancialListBoxExpenseItem>(); 
     } 

     /// <summary> 
     /// Method #1: Inserts an FinancialListBoxExpenseItem into Database 
     /// </summary> 
     /// <param name="item"></param> 
     /// <returns>Primary key of inserted item</returns> 
     public int insertExpenseItem(FinancialListBoxExpenseItem item) 
     { 
      int primaryKey = 0; 
      connection.RunInTransaction(() => 
          { 
           connection.Insert(item); 
           primaryKey = item.expenseID; 
          }); 

      return primaryKey; 
     } 

    /// <summary> 
    /// Method #2: Inserts an FinancialListBoxExpenseItem into Database 
    /// </summary> 
    /// <param name="item"></param> 
    /// <returns>Primary key of inserted item</returns> 
    public int insertExpenseItem2(FinancialListBoxExpenseItem item) 
    { 
     int primaryKey = 0; 
     connection.RunInTransaction(() => 
         { 
          connection.Insert(item); 
          primaryKey = connection.ExecuteScalar<int>("SELECT last_insert_rowid()"); 
         }); 

     return primaryKey; 
    } 
} 

FinancialListBoxItem कक्षा में आईडी संपत्ति इस तरह दिखता है:

public class FinancialListBoxExpenseItem : Money.Common.BindableBase 
    { 

     private int _expenseID = 0; 
     [AutoIncrement, PrimaryKey] 
     public int expenseID 
     { 
      get 
      { 
       return _expenseID; 
      } 

      set 
      { 
       this.SetProperty<int>(ref _expenseID, value); 
      } 
     } 
} 

मुझे लगता है कि आप अपने pk स्तंभ 'ईद' के लिए एक अलग नाम चुनने की सलाह देंगे। मुझे नहीं पता कि आईडी एक आंतरिक कीवर्ड की तरह कुछ है या नहीं। संपादित करें: ठीक है यह एक SQLite कीवर्ड नहीं है, लेकिन आईडी एक उचित नाम वैसे भी (स्रोत: SQLite Keywords) नहीं है

-1
public List<int[]> CreateSymbolByName(string SymbolName, bool AcceptDuplicates) 
    { 
     if (! AcceptDuplicates) // check if "AcceptDuplicates" flag is set 
     { 
      List<int[]> ExistentSymbols = GetSymbolsByName(SymbolName, 0, 10); // create a list of int arrays with existent records 
      if (ExistentSymbols.Count > 0) return ExistentSymbols; //(1) return existent records because creation of duplicates is not allowed 
     } 
     List<int[]> ResultedSymbols = new List<int[]>(); // prepare a empty list 
     int[] symbolPosition = { 0, 0, 0, 0 }; // prepare a neutral position for the new symbol 
     try // If SQL will fail, the code will continue with catch statement 
     { 
      //DEFAULT und NULL sind nicht als explizite Identitätswerte zulässig 
      string commandString = "INSERT INTO [simbs] ([En]) OUTPUT INSERTED.ID VALUES ('" + SymbolName + "') "; // Insert in table "simbs" on column "En" the value stored by variable "SymbolName" 
      SqlCommand mySqlCommand = new SqlCommand(commandString, SqlServerConnection); // initialize the query environment 
       SqlDataReader myReader = mySqlCommand.ExecuteReader(); // last inserted ID is recieved as any resultset on the first column of the first row 
       int LastInsertedId = 0; // this value will be changed if insertion suceede 
       while (myReader.Read()) // read from resultset 
       { 
        if (myReader.GetInt32(0) > -1) 
        { 
         int[] symbolID = new int[] { 0, 0, 0, 0 }; 
         LastInsertedId = myReader.GetInt32(0); // (2) GET LAST INSERTED ID 
         symbolID[0] = LastInsertedId ; // Use of last inserted id 
         if (symbolID[0] != 0 || symbolID[1] != 0) // if last inserted id succeded 
         { 
          ResultedSymbols.Add(symbolID); 
         } 
        } 
       } 
       myReader.Close(); 
      if (SqlTrace) SQLView.Log(mySqlCommand.CommandText); // Log the text of the command 
      if (LastInsertedId > 0) // if insertion of the new row in the table was successful 
      { 
       string commandString2 = "UPDATE [simbs] SET [IR] = [ID] WHERE [ID] = " + LastInsertedId + " ;"; // update the table by giving to another row the value of the last inserted id 
       SqlCommand mySqlCommand2 = new SqlCommand(commandString2, SqlServerConnection); 
       mySqlCommand2.ExecuteNonQuery(); 
       symbolPosition[0] = LastInsertedId; // mark the position of the new inserted symbol 
       ResultedSymbols.Add(symbolPosition); // add the new record to the results collection 
      } 
     } 
     catch (SqlException retrieveSymbolIndexException) // this is executed only if there were errors in the try block 
     { 
      Console.WriteLine("Error: {0}", retrieveSymbolIndexException.ToString()); // user is informed about the error 
     } 

    CreateSymbolTable(LastInsertedId); //(3) // Create new table based on the last inserted id 
    if (MyResultsTrace) SQLView.LogResult(LastInsertedId); // log the action 
    return ResultedSymbols; // return the list containing this new record 
} 
संबंधित मुद्दे

 संबंधित मुद्दे