在C#中使用SQLite数据库相对简单且灵活。以下是基本步骤:
步骤一:安装SQLite NuGet包
打开 Visual Studio 项目。
在解决方案资源管理器中右键点击项目名称,选择“管理 NuGet 程序包”。
在 NuGet 程序包管理器中搜索并安装 System.Data.SQLite 包。
步骤二:建立数据库连接
- using System.Data.SQLite;
-
- namespace YourNamespace
- {
- public class YourDatabaseClass
- {
- private SQLiteConnection connection;
-
- public YourDatabaseClass()
- {
- // 创建数据库连接
- connection = new SQLiteConnection("Data Source=YourDatabaseName.db;Version=3;");
- }
-
- public void OpenConnection()
- {
- if (connection.State != System.Data.ConnectionState.Open)
- connection.Open();
- }
-
- public void CloseConnection()
- {
- if (connection.State != System.Data.ConnectionState.Closed)
- connection.Close();
- }
- }
- }
-
步骤三:执行查询和操作
- public void ExecuteQuery(string query)
- {
- try
- {
- OpenConnection();
- SQLiteCommand cmd = new SQLiteCommand(query, connection);
- cmd.ExecuteNonQuery();
- }
- catch (SQLiteException ex)
- {
- // 处理异常
- }
- finally
- {
- CloseConnection();
- }
- }
-
示例:创建表格
- YourDatabaseClass database = new YourDatabaseClass();
- string createTableQuery = "CREATE TABLE IF NOT EXISTS MyTable (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age INTEGER)";
- database.ExecuteQuery(createTableQuery);
-
示例:选择数据
- string selectQuery = "SELECT * FROM MyTable";
- SQLiteCommand cmd = new SQLiteCommand(selectQuery, connection);
- SQLiteDataReader reader = cmd.ExecuteReader();
-
- while (reader.Read())
- {
- int id = reader.GetInt32(0);
- string name = reader.GetString(1);
- int age = reader.GetInt32(2);
-
- // 处理选择的数据
- }
-
注意事项:
确保安装了适当的SQLite NuGet包。
使用 try-catch 块来处理可能的异常。
使用 using 语句来确保资源正确释放,例如 SQLiteConnection、SQLiteCommand 和 SQLiteDataReader。