5).选择合适的包并安装。
string connectionString = "Data Source=MyDatabase.db;Version=3;";
using System.Data.SQLite; // 对于System.Data.SQLite // 或 using Microsoft.Data.Sqlite; // 对于Microsoft.Data.Sqlite string connectionString = "Data Source=MyDatabase.db;Version=3;"; using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { connection.Open(); // 执行数据库操作 }2. 执行SQL命令
using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { connection.Open(); string sql = "CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL);"; using (SQLiteCommand command = new SQLiteCommand(sql, connection)) { command.ExecuteNonQuery(); } }3. 查询数据
using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { connection.Open(); string sql = "SELECT * FROM Users;"; using (SQLiteCommand command = new SQLiteCommand(sql, connection)) using (SQLiteDataReader reader = command.ExecuteReader()) { while (reader.Read()) { int id = reader.GetInt32(0); string name = reader.GetString(1); Console.WriteLine($"User ID: {id}, Name: {name}"); } } }4. 使用参数化查询
using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { connection.Open(); // 堆代码 duidaima.com string sql = "INSERT INTO Users (Name) VALUES (@Name);"; using (SQLiteCommand command = new SQLiteCommand(sql, connection)) { command.Parameters.AddWithValue("@Name", "John Doe"); command.ExecuteNonQuery(); } }5. 事务处理
using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { connection.Open(); SQLiteTransaction transaction = connection.BeginTransaction(); try { using (SQLiteCommand command = new SQLiteCommand(connection)) { command.Connection = connection; command.Transaction = transaction; command.CommandText = "INSERT INTO Users (Name) VALUES ('Jane Doe');"; command.ExecuteNonQuery(); command.CommandText = "UPDATE Users SET Name = 'Jane Smith' WHERE Name = 'Jane Doe';"; command.ExecuteNonQuery(); transaction.Commit(); } } catch (Exception ex) { transaction.Rollback(); Console.WriteLine(ex.Message); } }技巧