300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 手把手教你使用C#操作SQLite数据库 新建数据库 创建表 插入 查询 删除 运算符 like...

手把手教你使用C#操作SQLite数据库 新建数据库 创建表 插入 查询 删除 运算符 like...

时间:2021-04-06 07:22:12

相关推荐

手把手教你使用C#操作SQLite数据库 新建数据库 创建表 插入 查询 删除 运算符 like...

目录:

一、新建项目,添加引用

二、创建数据库

三、创建表

四、插入数据

五、查询数据

六、删除数据

七、运算符

八、like语句

我的环境配置:windows 64,VS,SQLite(点击下载),System.Data.SQLite.DLL(点击下载)。

一、新建项目,添加引用

1.在VS中新建一个控制台应用程序,如下图

2.添加引用

将下载的System.Data.SQLite.DLL复制到新建项目的路径下

在VS中找到项目,右键选择添加引用

浏览到dll路径下,添加进来。

代码中添加

using System.Data.SQLite;

添加类库CSQLiteHelper,用于存放SQLite操作方法(此代码原文链接./pukuimin1226/article/details/8516733)

具体代码

1 using System;2 using System.Collections.Generic;3 using System.Linq;4 using System.Text;5 using System.Data.SQLite;6 using System.Data;7 using System.Xml;8 using System.Text.RegularExpressions;9 using System.IO;10 11 namespace CSharp_SQLite12 {13public class CSQLiteHelper14{15 private string _dbName = "";16 private SQLiteConnection _SQLiteConn = null;//连接对象17 private SQLiteTransaction _SQLiteTrans = null; //事务对象18 private bool _IsRunTrans = false; //事务运行标识19 private string _SQLiteConnString = null; //连接字符串20 private bool _AutoCommit = false; //事务自动提交标识21 22 public string SQLiteConnString23 {24 set { this._SQLiteConnString = value; }25 get { return this._SQLiteConnString; }26 }27 28 public CSQLiteHelper(string dbPath)29 {30 this._dbName = dbPath;31 this._SQLiteConnString = "Data Source=" + dbPath;32 }33 34 /// <summary>35 /// 新建数据库文件36 /// </summary>37 /// <param name="dbPath">数据库文件路径及名称</param>38 /// <returns>新建成功,返回true,否则返回false</returns>39 static public Boolean NewDbFile(string dbPath)40 {41 try42 {43 SQLiteConnection.CreateFile(dbPath);44 return true;45 }46 catch (Exception ex)47 {48 throw new Exception("新建数据库文件" + dbPath + "失败:" + ex.Message);49 }50 }51 52 53 /// <summary>54 /// 创建表55 /// </summary>56 /// <param name="dbPath">指定数据库文件</param>57 /// <param name="tableName">表名称</param>58 static public void NewTable(string dbPath, string tableName)59 {60 61 SQLiteConnection sqliteConn = new SQLiteConnection("data source=" + dbPath);62 if (sqliteConn.State != System.Data.ConnectionState.Open)63 {64 sqliteConn.Open();65 SQLiteCommand cmd = new SQLiteCommand();66 cmd.Connection = sqliteConn;67 mandText = "CREATE TABLE " + tableName + "(Name varchar,Team varchar, Number varchar)";68 cmd.ExecuteNonQuery();69 }70 sqliteConn.Close();71 }72 /// <summary>73 /// 打开当前数据库的连接74 /// </summary>75 /// <returns></returns>76 public Boolean OpenDb()77 {78 try79 {80 this._SQLiteConn = new SQLiteConnection(this._SQLiteConnString);81 this._SQLiteConn.Open();82 return true;83 }84 catch (Exception ex)85 {86 throw new Exception("打开数据库:" + _dbName + "的连接失败:" + ex.Message);87 }88 }89 90 /// <summary>91 /// 打开指定数据库的连接92 /// </summary>93 /// <param name="dbPath">数据库路径</param>94 /// <returns></returns>95 public Boolean OpenDb(string dbPath)96 {97 try98 {99 string sqliteConnString = "Data Source=" + dbPath;100 101 this._SQLiteConn = new SQLiteConnection(sqliteConnString);102 this._dbName = dbPath;103 this._SQLiteConnString = sqliteConnString;104 this._SQLiteConn.Open();105 return true;106 }107 catch (Exception ex)108 {109 throw new Exception("打开数据库:" + dbPath + "的连接失败:" + ex.Message);110 }111 }112 113 /// <summary>114 /// 关闭数据库连接115 /// </summary>116 public void CloseDb()117 {118 if (this._SQLiteConn != null && this._SQLiteConn.State != ConnectionState.Closed)119 {120 if (this._IsRunTrans && this._AutoCommit)121 {122 mit();123 }124 this._SQLiteConn.Close();125 this._SQLiteConn = null;126 }127 }128 129 /// <summary>130 /// 开始数据库事务131 /// </summary>132 public void BeginTransaction()133 {134 this._SQLiteConn.BeginTransaction();135 this._IsRunTrans = true;136 }137 138 /// <summary>139 /// 开始数据库事务140 /// </summary>141 /// <param name="isoLevel">事务锁级别</param>142 public void BeginTransaction(IsolationLevel isoLevel)143 {144 this._SQLiteConn.BeginTransaction(isoLevel);145 this._IsRunTrans = true;146 }147 148 /// <summary>149 /// 提交当前挂起的事务150 /// </summary>151 public void Commit()152 {153 if (this._IsRunTrans)154 {155 mit();156 this._IsRunTrans = false;157 }158 }159 160 161}162 }

此时运行会报错,

警告 所生成项目的处理器架构“MSIL”与引用“System.Data.SQLite”的处理器架构“x86”不匹配。这种不匹配可能会导致运行时失败。请考虑通过配置管理器更改您的项目的目标处理器架构,以使您的项目与引用间的处理器架构保持一致,或者为引用关联一个与您的项目的目标处理器架构相符的处理器架构。

修改项目属性:x86。

再次运行,无误。

二、创建数据库

SQLite 是文件型的数据库,后缀名可以是".db3"、".db"或者“.sqlite”,甚至可以由你决定它的后缀。其中前3个类型是SQLite默认类型。

新建一个数据库文件,代码如下

1 /// <summary>2 /// 新建数据库文件3 /// </summary>4 /// <param name="dbPath">数据库文件路径及名称</param>5 /// <returns>新建成功,返回true,否则返回false</returns>6 static public Boolean NewDbFile(string dbPath)7 {8 try9 {10 SQLiteConnection.CreateFile(dbPath);11 return true;12 }13 catch (Exception ex)14 {15 throw new Exception("新建数据库文件" + dbPath + "失败:" + ex.Message);16 }17 }

三、创建表

1 /// <summary>2 /// 创建表3 /// </summary>4 /// <param name="dbPath">指定数据库文件</param>5 /// <param name="tableName">表名称</param>6 static public void NewTable(string dbPath, string tableName)7 {8 9 SQLiteConnection sqliteConn = new SQLiteConnection("data source=" + dbPath);10 if (sqliteConn.State != System.Data.ConnectionState.Open)11 {12 sqliteConn.Open();13 SQLiteCommand cmd = new SQLiteCommand();14 cmd.Connection = sqliteConn;15 mandText = "CREATE TABLE " + tableName + "(Name varchar,Team varchar, Number varchar)";16 cmd.ExecuteNonQuery();17 }18 sqliteConn.Close();19 }

例子:创建一个数据库文件 NBA.db3

然后创建表Stars,再创建表的列,Name,Team,Number。

1 class Program2{3 private static string dbPath = @"d:\NBA.db3";4 static void Main(string[] args)5 {6 //创建一个数据库db文件7 CSQLiteHelper.NewDbFile(dbPath); 8 //创建一个表9 string tableName = "Stars";10 CSQLiteHelper.NewTable(dbPath, tableName); 11 }12}

看下效果,数据库文件NBA的表Stars中有Name,Team和Number字段

四、插入数据

接下来,使用SQLite 的INSERT INTO语句用于向数据库的某个表中添加新的数据行。

先在Main()方法中创建一些数据。

1 List<object[]> starsDatas = new List<object[]>();2 starsDatas.Add(new object[] { "Garnett", "Timberwolves", "21" });3 starsDatas.Add(new object[] { "Jordan", "Bulls", "23" });4 starsDatas.Add(new object[] { "Kobe", "Lakers", "24" });5 starsDatas.Add(new object[] { "James", "Cavaliers", "23" });6 starsDatas.Add(new object[] { "Tracy", "Rockets", "1" });7 starsDatas.Add(new object[] { "Carter", "Nets", "15" });

将数据插入到表单中

1 private static void AddStars(List<object[]> stars)2 {3CSQLiteHelper sqlHelper = new CSQLiteHelper(dbPath);4sqlHelper.OpenDbConn();5string commandStr = "insert into Stars(Name,Team,Number) values(@name,@team,@number)";6foreach (var item in stars)7{8 if (isExist("Name", item[0].ToString()))9 {10 Console.WriteLine(item[0] + "的数据已存在!");11 continue;12 }13 else14 {15 sqlHelper.ExecuteNonQuery(commandStr, item);16 Console.WriteLine(item[0] + "的数据已保存!");17 Console.ReadKey();18 }19}20sqlHelper.CloseDbConn();21Console.ReadKey();22 23 }

效果如下:

五、查询数据

SQLite 的SELECT语句用于从 SQLite 数据库表中获取数据,以结果表的形式返回数据。这些结果表也被称为结果集。

一个简单的例子:查询一个球星所在的球队。

输入球星的名字,输出球队。

1 private static void Team(string name)2 {3CSQLiteHelper sqliteHelper = new CSQLiteHelper(dbPath);4sqliteHelper.OpenDbConn();5string commandText = @"select * from Stars where Name ='" + name+"'"; 6DataTable dt = sqliteHelper.Query(commandText).Tables[0];7if (dt.Rows.Count == 0)8{9 Console.WriteLine("查无此人!");10 Console.ReadLine();11 sqliteHelper.CloseDbConn();12 return;13}14string team = dt.Rows[0]["Team"].ToString(); 15sqliteHelper.CloseDbConn();16Console.WriteLine(name + "--" + team);17Console.ReadKey();18 }

1 static void Main(string[] args)2 {3Console.WriteLine("请输入一个Star:");4string name = Console.ReadLine();5Team(name);6 }

效果如下

六、删除数据

SQLite 的DELETE语句用于删除表中已有的记录。可以使用带有 WHERE 子句的 DELETE 查询来删除选定行,否则所有的记录都会被删除。

1 private static void Delete(string name)2 {3CSQLiteHelper sqliteHelper = new CSQLiteHelper(dbPath);4sqliteHelper.OpenDbConn();5string commandtext = "delete from Stars where Name = '" + name + "'";6sqliteHelper.ExecuteNonQuery(commandtext);7sqliteHelper.CloseDbConn();8Console.WriteLine(name + "被删除!");9 }

注意:delete语句与select语句不同,delete后直接跟from,不能写成:

"delete * from Stars where [condition];

调用一下

Console.WriteLine("删除球星:");string starName = Console.ReadLine();Delete(starName);

删除前:

删除后:

七、运算符

运算符是一个保留字或字符,主要用于 SQLite 语句的 WHERE 子句中执行操作,如比较和算术运算。

运算符用于指定 SQLite 语句中的条件,并在语句中连接多个条件。

可以直接在SQLite语句中加入运算符,= - * / % > < = >= <= 等等

参考 SQLite运算符|菜鸟教程

例:

下面代码是首先插入一些NBA球员的信息,然后筛选出球衣号码大于10的球员:

1 using System;2 using System.Collections.Generic;3 using System.Data.SQLite;4 using System.Data;5 using System.IO;6 using mon;7 using System.Diagnostics;8 9 10 namespace CSharp_SQLite11 {12class Program13{14 15 static void Main(string[] args)16 {17 string dbPath = "NBAStars.nba";18 Stopwatch timer = new Stopwatch();19 timer.Start();20 CSQLiteHelper sqlhelper = new CSQLiteHelper(dbPath);21 sqlhelper.OpenDbConn();22 sqlhelper.BeginTransaction();23 sqlhelper.ExecuteNonQuery("delete from Stars");24 #region 球员信息25 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Michael Jordan','Bulls','23')");26 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('James Harden','Rockets','13')");27 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Lebron James','Cavaliers','23')");28 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Tracy Mcgrady','Rockets','1')");29 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Yao Ming','Rockets','11')");30 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Kevin Garnett','Timberwolves','21')");31 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Tim Duncan','Supers','21')");32 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Vince Carter','Nets','15')");33 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Michael Carter Williams','76ers','10')");34 #endregion35 mit();36 sqlhelper.CloseDbConn();37 timer.Stop();38 Console.WriteLine("初始化数据库表单用时:" + timer.Elapsed);39 40 41 CSQLiteHelper sqlHelper = new CSQLiteHelper(dbPath);42 sqlHelper.OpenDbConn();43 sqlHelper.BeginTransaction();44 DataTable dt = sqlHelper.Query("select Name, Number from Stars where Number > 10").Tables[0];45 mit();46 sqlHelper.CloseDbConn();47 Console.WriteLine("球衣号码大于10的球员有:");48 for (int i = 0; i < dt.Rows.Count; i++)49 {50 Console.WriteLine(dt.Rows[i]["Name"] + "\t" + dt.Rows[i]["Number"]);51 }52 Console.ReadLine();53 }54 55}56 57 }

结果如下:

若想输出这些球员的球衣号码,则应该在select语句修改为

DataTable dt = sqlHelper.Query("select Name, Number from Stars where Number > 10").Tables[0];

将输出修改为

Console.WriteLine(dt.Rows[i]["Name"] +"\t"+ dt.Rows[i]["Number"]);

结果如下:

注:select语句中尽量不要使用select * from,那样会影响效率。

八、like语句

SQLite 的LIKE运算符是用来匹配通配符指定模式的文本值。如果搜索表达式与模式表达式匹配,LIKE 运算符将返回真(true),也就是 1。这里有两个通配符与 LIKE 运算符一起使用:

百分号 %下划线 _

百分号(%)代表零个、一个或多个数字或字符。下划线(_)代表一个单一的数字或字符。这些符号可以被组合使用。

语法

% 和 _ 的基本语法如下:

SELECT column_list FROM table_nameWHERE column LIKE 'XXXX%'or SELECT column_list FROM table_nameWHERE column LIKE '%XXXX%'orSELECT column_list FROM table_nameWHERE column LIKE 'XXXX_'orSELECT column_list FROM table_nameWHERE column LIKE '_XXXX'orSELECT column_list FROM table_nameWHERE column LIKE '_XXXX_'

您可以使用 AND 或 OR 运算符来结合 N 个数量的条件。在这里,XXXX 可以是任何数字或字符串值。

我们在球员中筛选出名字中包含James的球员

1 using System;2 using System.Collections.Generic;3 using System.Data.SQLite;4 using System.Data;5 using System.IO;6 using mon;7 using System.Diagnostics;8 9 10 namespace CSharp_SQLite11 {12class Program13{14 15 static void Main(string[] args)16 {17 string dbPath = "NBAStars.nba";18 Stopwatch timer = new Stopwatch();19 timer.Start();20 CSQLiteHelper sqlhelper = new CSQLiteHelper(dbPath);21 sqlhelper.OpenDbConn();22 sqlhelper.BeginTransaction();23 sqlhelper.ExecuteNonQuery("delete from Stars");24 #region 球员信息25 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Michael Jordan','Bulls','23')");26 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('James Harden','Rockets','13')");27 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Lebron James','Cavaliers','23')");28 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Tracy Mcgrady','Rockets','1')");29 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Yao Ming','Rockets','11')");30 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Kevin Garnett','Timberwolves','21')");31 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Tim Duncan','Supers','21')");32 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Vince Carter','Nets','15')");33 sqlhelper.ExecuteNonQuery("insert into Stars (Name,Team,Number) values('Michael Carter Williams','76ers','10')");34 #endregion35 mit();36 sqlhelper.CloseDbConn();37 timer.Stop();38 Console.WriteLine("初始化数据库表单用时:" + timer.Elapsed);39 40 41 CSQLiteHelper sqlHelper = new CSQLiteHelper(dbPath);42 sqlHelper.OpenDbConn();43 sqlHelper.BeginTransaction();44 DataTable dt = sqlHelper.Query("select Name, Number from Stars where Name like '%James%'").Tables[0];45 mit();46 sqlHelper.CloseDbConn();47 Console.WriteLine("名字中包含James的球员有:");48 for (int i = 0; i < dt.Rows.Count; i++)49 {50 Console.WriteLine(dt.Rows[i]["Name"] + "\t" + dt.Rows[i]["Number"]);51 }52 Console.ReadLine();53 }54 55}56 57 }

其中第44行代码DataTable dt = sqlHelper.Query("select Name, Number from Stars where Name like '%James%'").Tables[0];

%James%表示前面和后面包含零个、一个或多个数字或字符,也就是包含名字内James

运行结果如下

前言:

这一段来自SQLite官网

SQLite is an in-process library that implements aself-contained,serverless,zero-configuration,transactionalSQL database engine. The code for SQLite is in thepublic domainand is thus free for use for any purpose, commercial or private. SQLite is themost widely deployeddatabase in the world with more applications than we can count, including severalhigh-profile projects.

SQLite 是一个软件库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。SQLite 源代码不受版权限制。SQLite 是在世界上最广泛部署的 SQL 数据库引擎。SQLite是世界上应用最广泛的数据库,拥有着不计其数的应用,包括备受瞩目的项目。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。