using System;
using System.Data.SQLite;
class Program
{
static void Main()
{
// 创建一个新的 SQLite 数据库连接
using (SQLiteConnection connection = new SQLiteConnection("Data Source=mydatabase.db;Version=3;"))
{
try
{
// 打开数据库连接
connection.Open();
Console.WriteLine("数据库连接成功");
// 创建一个表
string createTableQuery = "CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY, Name TEXT, Age INTEGER)";
using (SQLiteCommand command = new SQLiteCommand(createTableQuery, connection))
{
command.ExecuteNonQuery();
Console.WriteLine("表创建成功");
}
// 插入数据
string insertQuery = "INSERT INTO Users (Name, Age) VALUES (@Name, @Age)";
using (SQLiteCommand command = new SQLiteCommand(insertQuery, connection))
{
command.Parameters.AddWithValue("@Name", "John Doe");
command.Parameters.AddWithValue("@Age", 30);
command.ExecuteNonQuery();
Console.WriteLine("数据插入成功");
}
// 查询数据
string selectQuery = "SELECT * FROM Users";
using (SQLiteCommand command = new SQLiteCommand(selectQuery, connection))
{
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"ID: {reader["Id"]}, Name: {reader["Name"]}, Age: {reader["Age"]}");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {ex.Message}");
}
finally
{
// 关闭数据库连接
connection.Close();
Console.WriteLine("数据库连接已关闭");
}
}
}
}
SQLiteConnection 类创建一个新的数据库连接,并指定数据库文件路径和版本。connection.Open() 方法打开数据库连接。CREATE TABLE SQL 语句创建一个名为 Users 的表,包含 Id, Name, 和 Age 列。INSERT INTO SQL 语句向 Users 表中插入一条记录。为了防止 SQL 注入攻击,使用参数化查询。SELECT SQL 语句从 Users 表中读取所有记录,并通过 SQLiteDataReader 类遍历结果集。try-catch-finally 块来捕获并处理可能发生的异常,确保在任何情况下都能正确关闭数据库连接。希望这段代码和解释对你有帮助!
上一篇:c# list转string
下一篇:c#连接oracle数据库
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站