如何将List的内容添加到SQLite数据库?

问题描述:

我创建了一个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; } 
    } 

任何人都可以给我一些建议或关于如何从列表中获取数据并插入表中的建议?

这是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); 
}