2016-08-20 79 views
1

我創建了一個SqliteConnection到我的數據庫,並在數據庫中,我有一個表:如何將List的內容添加到SQLite數據庫?

var conn = new SqliteConnection("Data Source=" + db); 

     // Set the structure of the database 
     if (!exists) 
     { 
      var commands = new[] { 
     "CREATE TABLE Phrases (Id INTEGER PRIMARY KEY AUTOINCREMENT, Keyword TEXT, Translation1 TEXT, Translation2 TEXT)" 
     }; 
      conn.Open(); 
      conn.Open(); 
      foreach (var cmd in commands) 
      { 
       using (var c = conn.CreateCommand()) 
       { 
        c.CommandText = cmd; 
        c.CommandType = CommandType.Text; 
        c.ExecuteNonQuery(); 
       } 
      } 
      conn.Close(); 

我想什麼做的是一個列表的內容插入到該表:

List<Phrase> 

    public partial class Phrase 
    { 
     public string Keyword { get; set; } 
     public string Translation1 { get; set; } 
     public string Translation2 { get; set; } 
    } 

任何人都可以給我一些建議或關於如何從列表中獲取數據並插入表中的建議?

回答

1

這是INSERT SQLite語法,它需要C#中的命令參數。

您可以將連接和命令封裝到usingtry/catch語句中。

string db = "MyDB.s3db"; 
List<Phrase> phraseList = new List<Phrase>() 
{ 
    new Phrase() { Keyword = "start", Translation1="Hi!", Translation2="Привет!" }, 
    new Phrase() { Keyword = "end", Translation1="Bye!", Translation2="Пока!" }, 
}; 

try 
{ 
    using (var conn = new SQLiteConnection("Data Source=" + db)) 
    { 
     conn.Open(); 

     string createCmd = 
      "CREATE TABLE IF NOT EXISTS Phrases (Id INTEGER PRIMARY KEY AUTOINCREMENT, Keyword TEXT, Translation1 TEXT, Translation2 TEXT)"; 
     using (var cmd = new SQLiteCommand(createCmd, conn)) 
     { 
      cmd.ExecuteNonQuery(); 
     } 

     string insertCmd = 
      "INSERT INTO Phrases (Keyword, Translation1, Translation2) VALUES(?,?,?)"; 
     foreach (Phrase phrase in phraseList) 
     { 
      using (var cmd = new SQLiteCommand(insertCmd, conn)) 
      { 
       cmd.Parameters.AddWithValue("@Keyword",phrase.Keyword); 
       cmd.Parameters.AddWithValue("@Translation1", phrase.Translation1); 
       cmd.Parameters.AddWithValue("@Translation2", phrase.Translation2); 
       cmd.ExecuteNonQuery(); 
      } 
     } 
     conn.Close(); 
    } 
} 
catch (Exception exc) 
{ 
    Debug.WriteLine(exc.Message); 
    Debug.WriteLine(exc.StackTrace); 
} 
相關問題