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的资料请关注代码网其它相关文章!
发表评论