C# Winform 数据库操作:使用 System.Data.Sqlite 实现 SQLite 数据库交互
- 准备工作
-
下载 SQLite 的最新版安装包,安装 SQLite。
-
在 Visual Studio 中新建一个 Winform 应用程序,添加 System.Data.Sqlite 引用。
-
在项目中添加 SQLite 的数据库文件,例如 test.db。
-
在项目中添加 SQLite 的连接字符串,例如 'Data Source=test.db;Version=3;'
- 创建数据库表
使用 SQLite 的 CREATE TABLE 语句创建数据库表。
using System.Data.SQLite;
// 连接字符串
string connStr = "Data Source=test.db;Version=3;";
// SQL 语句
string sql = "CREATE TABLE IF NOT EXISTS Student (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)";
// 创建连接对象
using (SQLiteConnection conn = new SQLiteConnection(connStr))
{
// 打开连接
conn.Open();
// 创建命令对象
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
// 执行命令
cmd.ExecuteNonQuery();
}
}
- 插入数据
使用 SQLite 的 INSERT INTO 语句插入数据。
using System.Data.SQLite;
// 连接字符串
string connStr = "Data Source=test.db;Version=3;";
// SQL 语句
string sql = "INSERT INTO Student (name, age) VALUES ('Tom', 18)";
// 创建连接对象
using (SQLiteConnection conn = new SQLiteConnection(connStr))
{
// 打开连接
conn.Open();
// 创建命令对象
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
// 执行命令
cmd.ExecuteNonQuery();
}
}
- 查询数据
使用 SQLite 的 SELECT 语句查询数据。
using System.Data.SQLite;
// 连接字符串
string connStr = "Data Source=test.db;Version=3;";
// SQL 语句
string sql = "SELECT * FROM Student";
// 创建连接对象
using (SQLiteConnection conn = new SQLiteConnection(connStr))
{
// 打开连接
conn.Open();
// 创建命令对象
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
// 执行命令
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
// 遍历结果集
while (reader.Read())
{
// 获取列值
int id = reader.GetInt32(reader.GetOrdinal("id"));
string name = reader.GetString(reader.GetOrdinal("name"));
int age = reader.GetInt32(reader.GetOrdinal("age"));
Console.WriteLine("{0} {1} {2}", id, name, age);
}
}
}
}
- 更新数据
使用 SQLite 的 UPDATE 语句更新数据。
using System.Data.SQLite;
// 连接字符串
string connStr = "Data Source=test.db;Version=3;";
// SQL 语句
string sql = "UPDATE Student SET age = 19 WHERE name = 'Tom'";
// 创建连接对象
using (SQLiteConnection conn = new SQLiteConnection(connStr))
{
// 打开连接
conn.Open();
// 创建命令对象
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
// 执行命令
cmd.ExecuteNonQuery();
}
}
- 删除数据
使用 SQLite 的 DELETE 语句删除数据。
using System.Data.SQLite;
// 连接字符串
string connStr = "Data Source=test.db;Version=3;";
// SQL 语句
string sql = "DELETE FROM Student WHERE name = 'Tom'";
// 创建连接对象
using (SQLiteConnection conn = new SQLiteConnection(connStr))
{
// 打开连接
conn.Open();
// 创建命令对象
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
// 执行命令
cmd.ExecuteNonQuery();
}
}
以上是 C# Winform 通过 System.Data.Sqlite 实现数据库操作的简单介绍,希望对你有帮助。
原文地址: https://www.cveoy.top/t/topic/mJC3 著作权归作者所有。请勿转载和采集!