C#连接SQLite数据库并实现基本操作
作者:我曾经是个程序员
本文介绍了SQLite,一个轻量级的跨平台数据库管理系统,以及如何在C#中使用System.Data.SQLite库进行操作,包括创建、修改和查询数据库,以及使用SQLiteHelper类简化SQL使用,此外,还提到了DB文件查看工具SQLiteSpy的应用,需要的朋友可以参考下
1.安装并引用System.Data.SQLite
通过NuGet包管理器安装,Install-Package System.Data.SQLite
2.创建数据库
string dbFilename = "test.db"; if (!File.Exists(dbFilename)) { SQLiteConnection.CreateFile(dbFilename); }
3.设置数据库密码
string connectionString = string.Format("Data Source={0};Version=3;",dbFilename); using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { connection.Open();//打开数据库 connection.ChangePassword("123456");//设置密码 }
4.连接数据库
string connectionString =string.Format("Data Source={0}; Version=3; Password={1};",dbFilename,"123456"); using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { connection.Open(); }
5.创建表
using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { connection.Open(); string commandText = "CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR(100), Code VARCHAR(100),Password VARCHAR(100))"; using (SQLiteCommand command = new SQLiteCommand(commandText, connection)) { command.ExecuteNonQuery();//执行sql } }
6.添加数据
using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { connection.Open(); string commandText = "insert into Users (Name, Code,Password) values (@name, @code,@password)"; using (SQLiteCommand command = new SQLiteCommand(commandText, connection)) { // 设置参数值 command.Parameters.AddWithValue("@name", "管理员"); command.Parameters.AddWithValue("@code", "admin"); command.Parameters.AddWithValue("@password", "123456"); // 执行语句 command.ExecuteNonQuery(); } }
7.修改数据
using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { connection.Open(); string commandText = "update Users SET Password=@password WHERE Code = @code"; using (SQLiteCommand command = new SQLiteCommand(commandText, connection)) { // 设置参数值 command.Parameters.AddWithValue("@code", "admin"); command.Parameters.AddWithValue("@password", "admin123456"); // 执行语句 command.ExecuteNonQuery(); } }
8.查询数据
using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { connection.Open(); string commandText = "select * from Users"; using (SQLiteCommand command = new SQLiteCommand(commandText, connection)) { using (SQLiteDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Console.WriteLine($"ID: {reader["Id"]}, 名称: {reader["Name"]}, 编码: {reader["Code"]}"); } } } }
9.删除数据
using (SQLiteConnection connection = new SQLiteConnection(connectionString)) { connection.Open(); string commandText = "delete from Users where Code = @code"; using (SQLiteCommand command = new SQLiteCommand(sql, connection)) { // 设置参数值 command.Parameters.AddWithValue("@code", "admin"); // 执行语句 command.ExecuteNonQuery(); } }
以上就是C#连接SQLite数据库并实现基本操作的详细内容,更多关于C#连接SQLite的资料请关注脚本之家其它相关文章!