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库

Logo

一站式 AI 云服务平台

更多推荐