演示创建数据库、创建表、插入数据、查询数据的操作。
注意事项:
1.确保已经安装了 SQLite 编译器库。在 Visual Studio 中,可以通过以下步骤安装: - 打开 Visual Studio,点击 "工具" -> "NuGet 包管理器" -> "管理解决方案的 NuGet 包" - 在搜索框中输入 "SQLite",然后安装 "System.Data.SQLite" 包。
2.确保添加了System.Data.SQLite.dll的引用。
操作步骤:
(1)创建了一个名为 "test.db" 的SQLite数据库文件。
(2)通过 SQLiteConnection类建立与数据库的连接。
(3)使用 SQLiteCommand类执行了创建表和插入数据的操作,并通过参数化查询的方式避免了SQL注入的风险。
(4)使用 SQLiteDataReader类执行了查询数据的操作,并将查询结果打印到控制台上。
以下是控制台操作SQLite示例代码:
using System;
using System.Data.SQLite;
namespace SQLiteExample
{
class Program
{
static void Main(string[] args)
{
string dataSource = "test.db"; // 数据库文件名
// 连接数据库
using (SQLiteConnection connection = new SQLiteConnection($"Data Source={dataSource};Version=3;"))
{
connection.Open(); // 打开连接
// 创建表
string createTableQuery = "CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY, Name TEXT, Age INT,Phone TEXT)";
using (SQLiteCommand createTableCommand = new SQLiteCommand(createTableQuery, connection))
{
createTableCommand.ExecuteNonQuery(); // 执行创建表的SQL语句
}
// 插入数据
string insertDataQuery = "INSERT INTO Users (Name, Age, Phone) VALUES (@Name, @Age, @Phone)";
using (SQLiteCommand insertDataCommand = new SQLiteCommand(insertDataQuery, connection))
{
insertDataCommand.Parameters.AddWithValue("@Name", "John"); // 设置参数值,避免SQL注入
insertDataCommand.Parameters.AddWithValue("@Age", 25);
insertDataCommand.Parameters.AddWithValue("@Phone", "123456");
insertDataCommand.ExecuteNonQuery(); // 执行插入数据的SQL语句
}
// 查询数据
string selectDataQuery = "SELECT * FROM Users";
using (SQLiteCommand selectDataCommand = new SQLiteCommand(selectDataQuery, connection))
{
using (SQLiteDataReader reader = selectDataCommand.ExecuteReader()) // 执行查询并返回结果集
{
while (reader.Read()) // 逐行读取结果集
{
int id = Convert.ToInt32(reader["Id"]); // 读取每一行的ID、Name、Age、Phone列的值
string name = Convert.ToString(reader["Name"]);
int age = Convert.ToInt32(reader["Age"]);
string phone = Convert.ToString(reader["Phone"]);
Console.WriteLine($"ID: {id}, Name: {name}, Age: {age}, Phone: {phone}"); // 打印查询结果
}
}
}
}
Console.ReadKey();
}
}
}