我已经为我的数据库创建了一个SqliteConnection,在该数据库中我有一个表:
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的内容插入到该表中:
List<Phrase>
public partial class Phrase
{
public string Keyword { get; set; }
public string Translation1 { get; set; }
public string Translation2 { get; set; }
}
任何人都可以就如何从列表中获取数据并插入表格给我一些建议或建议吗?
答案 0 :(得分:1)
这是INSERT SQLite语法,它需要C#中的命令参数。
您可以将连接和命令包装到using
和try/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);
}