SQLite数据库--C#帮助类SQLiteHelper

文章展示了如何在C#中使用SQLiteHelper类来执行数据库的基本操作,包括插入、查询、更新和删除数据。SQLiteHelper类封装了SQLite连接和命令,简化了操作流程。在使用前,需通过NuGet安装System.Data.SQLite库。

1.SQLiteHelper 代码:

using System.Data.SQLite;

public class SQLiteHelper
{
    private SQLiteConnection connection;

    public SQLiteHelper(string dbPath)
    {
        connection = new SQLiteConnection($"Data Source={dbPath};Version=3;");
        connection.Open();
    }

    public void Close()
    {
        connection.Close();
    }

    public void ExecuteNonQuery(string sql)
    {
        using (SQLiteCommand command = new SQLiteCommand(sql, connection))
        {
            command.ExecuteNonQuery();
        }
    }

    public object ExecuteScalar(string sql)
    {
        using (SQLiteCommand command = new SQLiteCommand(sql, connection))
        {
            return command.ExecuteScalar();
        }
    }

    public SQLiteDataReader ExecuteReader(string sql)
    {
        using (SQLiteCommand command = new SQLiteCommand(sql, connection))
        {
            return command.ExecuteReader();
        }
    }

    public DataTable ExecuteDataTable(string sql)
    {
        using (SQLiteCommand command = new SQLiteCommand(sql, connection))
        {
            using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(command))
            {
                DataTable dataTable = new DataTable();
                adapter.Fill(dataTable);
                return dataTable;
            }
        }
    }
}

2.实例调用:

SQLiteHelper helper = new SQLiteHelper("test.db");

// 插入数据
helper.ExecuteNonQuery("INSERT INTO user (name, age) VALUES ('Tom', 20)");

// 查询数据
SQLiteDataReader reader = helper.ExecuteReader("SELECT * FROM user");
while (reader.Read())
{
    string name = reader.GetString(0);
    int age = reader.GetInt32(1);
    Console.WriteLine($"name: {name}, age: {age}");
}

// 更新数据
helper.ExecuteNonQuery("UPDATE user SET age = 21 WHERE name = 'Tom'");

// 删除数据
helper.ExecuteNonQuery("DELETE FROM user WHERE name = 'Tom'");

helper.Close();

3.使用注意事项:

注意:在使用SQLite数据库时,需要先安装SQLite的.NET库。可以通过NuGet安装System.Data.SQLite库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值