前言
我们在开发应用是经常会需要用到一些数据的存储,存储的方式有多种,使用数据库是一种比较受大家欢迎的方式。但是对于一些小型的应用,如一些移动app,通常的数据库过于庞大,而轻便的sqlite则能解决这一问题。不但操作方便,而且只需要要一个文件即可,在这里我们来说一说使用c#语言操作sqlite数据库。
一、nuget引入sqlite库
在vs菜单:工具→nuget包管理器→管理解决方案的nuget程序包 打开nuget解决方案窗口。
搜索 sqlite,选择官方的库安装到指定的项目中。:
提示:system.data.sqlite 分为 x86 和 x64 版本,这里推荐使用nuget自动安装。使用 any cpu 编译的时候,会自动拷贝32位和64位 interop dll文件到子目录中。程序运行的时候会根据电脑的运行环境自动选择合适的dll。
二、dbhelper类库
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
using system.collections.generic;
using system.data;
using system.data.sqlite;
using system.configuration;
using system.data.sqlclient;
//using mysql.data.mysqlclient;
namespace consoleapp5
{
public class dbhelper
{
private readonly static string connstr = configurationmanager.connectionstrings[ "data source=mesclient.sqlite;version=3" ].connectionstring;
//获取 appsetting 设置的值
//private readonly static string appstr = configurationmanager.appsettings["testkey"];
//获取 connection 对象
public static idbconnection createconnection()
{
idbconnection conn = new sqliteconnection(connstr); //mysqlconnection //sqlconnection
conn.open();
return conn;
}
//执行非查询语句
public static int executenonquery(idbconnection conn, string sql, dictionary< string , object > parameters)
{
using (idbcommand cmd = conn.createcommand())
{
cmd.commandtext = sql;
foreach (keyvaluepair< string , object > keyvaluepair in parameters)
{
idbdataparameter parameter = cmd.createparameter();
parameter.parametername = keyvaluepair.key;
parameter.value = keyvaluepair.value;
cmd.parameters.add(parameter);
}
return cmd.executenonquery();
}
}
//执行非查询语句-独立连接
public static int executenonquery( string sql, dictionary< string , object > parameters)
{
using (idbconnection conn = createconnection())
{
return executenonquery(conn, sql, parameters);
}
}
//查询首行首列
public static object executescalar(idbconnection conn, string sql, dictionary< string , object > parameters)
{
using (idbcommand cmd = conn.createcommand())
{
cmd.commandtext = sql;
foreach (keyvaluepair< string , object > keyvaluepair in parameters)
{
idbdataparameter parameter = cmd.createparameter();
parameter.parametername = keyvaluepair.key;
parameter.value = keyvaluepair.value;
cmd.parameters.add(parameter);
}
return cmd.executescalar();
}
}
//查询首行首列-独立连接
public static object executescalar( string sql, dictionary< string , object > parameters)
{
using (idbconnection conn = createconnection())
{
return executescalar(conn, sql, parameters);
}
}
//查询表
public static datatable executequery(idbconnection conn, string sql, dictionary< string , object > parameters)
{
datatable dt = new datatable();
using (idbcommand cmd = conn.createcommand())
{
cmd.commandtext = sql;
foreach (keyvaluepair< string , object > keyvaluepair in parameters)
{
idbdataparameter parameter = cmd.createparameter();
parameter.parametername = keyvaluepair.key;
parameter.value = keyvaluepair.value;
cmd.parameters.add(parameter);
}
using (idatareader reader = cmd.executereader())
{
dt.load(reader);
}
}
return dt;
}
//查询表--独立连接
public static datatable executequery( string sql, dictionary< string , object > parameters)
{
using (idbconnection conn = createconnection())
{
return executequery(conn, sql, parameters);
}
}
}
}
|
三、基本使用
1. 判断数据文件是否存在
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
/// <summary>
/// 检查数据库是否存在不存在创建
/// </summary>
/// <returns></returns>
public static bool checkdatabase()
{
try
{
//判断数据文件是否存在
bool dbexist = file.exists( "mesclient.sqlite" );
if (!dbexist)
{
sqliteconnection.createfile( "mesclient.sqlite" );
}
return true ;
}
catch (exception)
{
return false ;
}
}
|
2. 判断表是否存在
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
/// <summary>
/// 检查数据表是否存在,不存在创建
/// </summary>
/// <returns></returns>
public static bool checkdatatable( string connstr)
{
try
{
using (sqliteconnection conn = new sqliteconnection(connstr))
using (sqlitecommand cmd = conn.createcommand())
{
conn.open();
cmd.commandtext = "select count(*) from sqlite_master where type = 'table' and name = 'serverinfo'" ;
object ob = cmd.executescalar();
long tablecount = convert.toint64(ob);
if (tablecount == 0)
{
//创建表
cmd.commandtext = @"
begin;
create table serverinfo
(id integer primary key autoincrement,name text,
url text,delaytime integer,usagecounter integer,
status integer,createtime datetime);
create unique index idx_serverinfo on serverinfo (name);
commit;
" ;
//此语句返回结果为0
int rowcount = cmd.executenonquery();
return true ;
}
else if (tablecount > 1)
{
return false ;
}
else
{
return true ;
}
}
}
catch (exception ex)
{
return false ;
}
}
|
3. 查询
1
2
3
4
5
6
7
8
9
10
11
|
string sql = "select * from serverinfo where name =@servername and url = @url and date(createtime)=date(@date);" ;
dictionary< string , object > parameters = new dictionary< string , object >();
parameters.add( "servername" ,endpointelement.name);
parameters.add( "url" , endpointelement.address);
parameters.add( "date" , datetime.now.tostring( "yyyy-mm-dd" ));
datatable dt=sqlitehelper.executequery(connstr, sql, parameters);
if (dt.rows.count>0)
{
usagecounter = dt.rows[0].field< long >( "usagecounter" );
gettime = dt.rows[0].field<datetime>( "createtime" );
}
|
4. 新增/修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//存在更新,不存在插入
string updatesql = "replace into serverinfo(name,url,delaytime,usagecounter, status,createtime) values(@name,@url,@delaytime,@usagecounter,@status, @createtime)" ;
dictionary< string , object > ups = new dictionary< string , object >();
ups.add( "name" , name);
ups.add( "url" , url);
ups.add( "delaytime" , delaytime);
ups.add( "usagecounter" , usagecounter);
ups.add( "status" , status);
ups.add( "createtime" , datetime.now.tostring( "yyyy-mm-dd hh:mm:ss" ));
int count= sqlitehelper.executenonquery(connstr, updatesql, ups);
if (count>0)
{
return true ;
}
else
{
return false ;
}
|
5. 删除
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
//删除记录
string updatesql =
"delete from serverinfo where content=@content and flag=@flag;" ;
dictionary< string , object > updateparameters = new dictionary< string , object >();
updateparameters.add( "content" , content);
updateparameters.add( "flag" , flag);
int count = sqlitehelper.executenonquery(connstr, updatesql, updateparameters);
if (count > 0)
{
return true ;
}
else
{
return false ;
}
|
四、参考文章
- Create SQLite Database and table
- Writing to a SQLite Database in C#
- SQLite with VS2012 and .NET 4.5 — ANY CPU Build
- how to check if a table exists in C#
- SQLite auto increment issue
- Inserting a date to SQLite
- SQLite REPLACE Statement
- sqlite select with condition on date
- Using SQLite how do I index columns in a CREATE TABLE statement?
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。
原文链接:https://renqiancheng.com/2018/11/C-SQLite-数据库使用说明.html