2016-08-20 11 views
1

내 데이터베이스에 SqliteConnection를 생성하고 해당 데이터베이스에 나는 테이블이 있습니다목록의 내용을 SQLite 데이터베이스에 추가하려면 어떻게해야합니까?

List<Phrase> 

    public partial class Phrase 
    { 
     public string Keyword { get; set; } 
     public string Translation1 { get; set; } 
     public string Translation2 { get; set; } 
    } 
: 내가하고 싶은 무엇

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(); 

그 테이블에 목록의 내용을 삽입하는 것입니다

누구든지 내게 조언을하거나 목록에서 데이터를 가져 와서 테이블에 삽입 할 수있는 방법에 대한 제안을 줄 수 있습니까?

답변

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); 
} 
관련 문제