C#操作SQLite方法实例详解
本文实例讲述了c#操作sqlite方法。分享给大家供大家参考。具体分析如下:
地址:
system.data.sqlite入手。。。
首先import/using:
connection和command:
private sqliteconnection conn; private sqlitecommand cmd;
连接db:
conn = new sqliteconnection("data source=c:\\test.db"); conn.open();
insert/update:
cmd = conn.createcommand(); cmd.commandtext = "insert into user(email,name) values ('email','name')"; cmd.executenonquery(); cmd.commandtext = "update userset name = 'codelicious' where id = 1"; cmd.executenonquery();
select:
cmd.commandtext = "select id, name from user"; sqlitedatareader reader = cmd.executereader(); if (reader.hasrows) { while (reader.read()) { console.writeline("id: " + reader.getint16(0)); console.writeline("name: " + reader.getstring(1)); } }
模板程序:
using system; using system.data; using system.data.common; using system.data.sqlite; namespace sqlitequerybrowser { /// <summary> /// 说明:这是一个针对system.data.sqlite的数据库常规操作封装的通用类。 /// </summary> public class sqlitedbhelper { private string connectionstring = string.empty; /// <summary> /// 构造函数 /// </summary> /// <param name="dbpath">sqlite数据库文件路径</param> public sqlitedbhelper(string dbpath) { this.connectionstring = "data source=" + dbpath; } /// <summary> /// 创建sqlite数据库文件 /// </summary> /// <param name="dbpath">要创建的sqlite数据库文件路径</param> public static void createdb(string dbpath) { using (sqliteconnection connection = new sqliteconnection("data source=" + dbpath)) { connection.open(); using (sqlitecommand command = new sqlitecommand(connection)) { command.commandtext = "create table demo(id integer not null primary key autoincrement unique)"; command.executenonquery(); command.commandtext = "drop table demo"; command.executenonquery(); } } } /// <summary> /// 对sqlite数据库执行增删改操作,返回受影响的行数。 /// </summary> /// <param name="sql">要执行的增删改的sql语句</param> /// <param name="parameters">执行增删改语句所需要的参数,参数必须以它们在sql语句中的顺序为准</param> /// <returns></returns> public int executenonquery(string sql, sqliteparameter[] parameters) { int affectedrows = 0; using (sqliteconnection connection = new sqliteconnection(connectionstring)) { connection.open(); using (dbtransaction transaction = connection.begintransaction()) { using (sqlitecommand command = new sqlitecommand(connection)) { command.commandtext = sql; if (parameters != null) { command.parameters.addrange(parameters); } affectedrows = command.executenonquery(); } transaction.commit(); } } return affectedrows; } /// <summary> /// 执行一个查询语句,返回一个关联的sqlitedatareader实例 /// </summary> /// <param name="sql">要执行的查询语句</param> /// <param name="parameters">执行sql查询语句所需要的参数,参数必须以它们在sql语句中的顺序为准</param> /// <returns></returns> public sqlitedatareader executereader(string sql, sqliteparameter[] parameters) { sqliteconnection connection = new sqliteconnection(connectionstring); sqlitecommand command = new sqlitecommand(sql, connection); if (parameters != null) { command.parameters.addrange(parameters); } connection.open(); return command.executereader(commandbehavior.closeconnection); } /// <summary> /// 执行一个查询语句,返回一个包含查询结果的datatable /// </summary> /// <param name="sql">要执行的查询语句</param> /// <param name="parameters">执行sql查询语句所需要的参数,参数必须以它们在sql语句中的顺序为准</param> /// <returns></returns> public datatable executedatatable(string sql, sqliteparameter[] parameters) { using (sqliteconnection connection = new sqliteconnection(connectionstring)) { using (sqlitecommand command = new sqlitecommand(sql, connection)) { if (parameters != null) { command.parameters.addrange(parameters); } sqlitedataadapter adapter = new sqlitedataadapter(command); datatable data = new datatable(); adapter.fill(data); return data; } } } /// <summary> /// 执行一个查询语句,返回查询结果的第一行第一列 /// </summary> /// <param name="sql">要执行的查询语句</param> /// <param name="parameters">执行sql查询语句所需要的参数,参数必须以它们在sql语句中的顺序为准</param> /// <returns></returns> public object executescalar(string sql, sqliteparameter[] parameters) { using (sqliteconnection connection = new sqliteconnection(connectionstring)) { using (sqlitecommand command = new sqlitecommand(sql, connection)) { if (parameters != null) { command.parameters.addrange(parameters); } sqlitedataadapter adapter = new sqlitedataadapter(command); datatable data = new datatable(); adapter.fill(data); return data; } } } /// <summary> /// 查询数据库中的所有数据类型信息 /// </summary> /// <returns></returns> public datatable getschema() { using (sqliteconnection connection = new sqliteconnection(connectionstring)) { connection.open(); datatable data=connection.getschema("tables"); connection.close(); //foreach (datacolumn column in data.columns) //{ // console.writeline(column.columnname); //} return data; } } } }
完整的程序例子:
using system; using system.collections.generic; using system.text; using system.data; using system.data.common; using system.data.sqlite; using sqlitequerybrowser; namespace sqlitedemo { class program { static void main(string[] args) { //createtable(); //insertdata(); showdata(); console.readline(); } public static void createtable() { string dbpath = "d:\\demo.db3"; //如果不存在改数据库文件,则创建该数据库文件 if (!system.io.file.exists(dbpath)) { sqlitedbhelper.createdb("d:\\demo.db3"); } sqlitedbhelper db = new sqlitedbhelper("d:\\demo.db3"); string sql = "create table test3(id integer not null primary key autoincrement unique,name char(3),typename varchar(50),adddate datetime,updatetime date,time time,comments blob)"; db.executenonquery(sql, null); } public static void insertdata() { string sql = "insert into test3(name,typename,adddate,updatetime,time,comments)values(@name,@typename,@adddate,@updatetime,@time,@comments)"; sqlitedbhelper db = new sqlitedbhelper("d:\\demo.db3"); for (char c = "a"; c <= "z"; c++) { for (int i = 0; i < 100; i++) { sqliteparameter[] parameters = new sqliteparameter[]{ new sqliteparameter("@name",c+i.tostring()), new sqliteparameter("@typename",c.tostring()), new sqliteparameter("@adddate",datetime.now), new sqliteparameter("@updatetime",datetime.now.date), new sqliteparameter("@time",datetime.now.toshorttimestring()), new sqliteparameter("@comments","just a test"+i) }; db.executenonquery(sql, parameters); } } } public static void showdata() { //查询从50条起的20条记录 string sql = "select * from test3 order by id desc limit 50 offset 20"; sqlitedbhelper db = new sqlitedbhelper("d:\\demo.db3"); using (sqlitedatareader reader = db.executereader(sql, null)) { while (reader.read()) { console.writeline("id:{0},typename{1}", reader.getint64(0), reader.getstring(1)); } } } } }
在实际情况中,采用通用类大批量插入数据会有些慢,这是因为在system.data.sqlite中的操作如果没有指定操作,则会被当做一个事物,如果需要一次性写入大量记录,则建议显式创建一个事物,在这个事务中完成所有的操作比较好,这样的话比每次操作创建一个事物的效率要提升很多。
最终利用vs2008提供的功能,可以看到里面的数据如下:
需要说明的是在system.data.sqlite中数据类型的规定不适很严格,从创建test3表的sql语句来看,表中adddate、updatetime、time分别是datetime、date、time类型字段,但实际上我们插入的时候没有按照这个规定,最终显示的结果也是尽量遵循数据库字段的定义。
总结
system.data.sqlite确实是一个非常小巧精悍的数据库,作为对sqlite的封装(sqlite可以在android等类型的手机上利用java访问),它依然是体较小,同比性能高、内存消耗小、无需安装仅需一个dll就可以运行的优点(如果在mobile手机上则需要两个文件),唯一的一个缺点是没有比较的gui(图形用户界面),不过正因为如此它才得以体积小。
在实际开发中没有图形用户界面可能有些不便,我们可以使用vs来查看和操作数据,我自己也做了一个小东东,便于管理和维护数据,界面如下:
如果你要开发数据量在10万条以下的应用,我建议你尝试使用一下system.data.sqlite,它或许是一个不错的选择。
public static void createtable() { string dbpath = "d:\\demo.db3"; //如果不存在改数据库文件,则创建该数据库文件 if (!system.io.file.exists(dbpath)) { sqlitedbhelper.createdb("d:\\demo.db3"); } sqlitedbhelper db = new sqlitedbhelper("d:\\demo.db3"); string sql = "create table test3(id integer not null primary key autoincrement unique,name char(3),typename varchar(50),adddate datetime,updatetime date,time time,comments blob)"; db.executenonquery(sql, null); } public static void insertdata() { string sql = "insert into test3(name,typename,adddate,updatetime,time,comments)values(@name,@typename,@adddate,@updatetime,@time,@comments)"; sqlitedbhelper db = new sqlitedbhelper("d:\\demo.db3"); for (char c = "a"; c <= "z"; c++) { for (int i = 0; i < 100; i++) { sqliteparameter[] parameters = new sqliteparameter[]{ new sqliteparameter("@name",c+i.tostring()), new sqliteparameter("@typename",c.tostring()), new sqliteparameter("@adddate",datetime.now), new sqliteparameter("@updatetime",datetime.now.date), new sqliteparameter("@time",datetime.now.toshorttimestring()), new sqliteparameter("@comments","just a test"+i) }; db.executenonquery(sql, parameters); } } } public static void showdata() { //查询从50条起的20条记录 string sql = "select * from test3 order by id desc limit 50 offset 20"; sqlitedbhelper db = new sqlitedbhelper("d:\\demo.db3"); using (sqlitedatareader reader = db.executereader(sql, null)) { while (reader.read()) { console.writeline("id:{0},typename{1}", reader.getint64(0), reader.getstring(1)); } } }
希望本文所述对大家的c#程序设计有所帮助。
下一篇: C#获取指定PDF文件页数的方法