当前位置: 移动技术网 > IT编程>开发语言>.net > 手把手教你使用C#连接并操作数据库SQLite,创建数据库,创建表,插入INSERT,查询SELECT,删除DELETE(持续更新)

手把手教你使用C#连接并操作数据库SQLite,创建数据库,创建表,插入INSERT,查询SELECT,删除DELETE(持续更新)

2018年05月31日  | 移动技术网IT编程  | 我要评论

深圳猎头,租房合同模板,金三角坤沙玩的女人

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


 前言:

这一段来自

SQLite is an in-process library that implements a , , , SQL database engine. The code for SQLite is in the  and is thus free for use for any purpose, commercial or private. SQLite is the  database in the world with more applications than we can count, including several 

 

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

 


 目录:

一、新建项目,添加引用

二、创建数据库

三、创建表

四、插入数据   INSERT INTO TABELNAME(FIELD1,FIELD2,FIELD3)  VALUES(@VALUE1,@VALUE2,@VALUE3)

五、查询数据   SELECT * FROM TABLENAME WHERE CONDITION

六、删除数据   DELETE FROM TABLENAME WHERE CONDITION

 

 


 


 

一、新建项目,添加引用

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

2.添加引用

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

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

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

代码中添加

using System.Data.SQLite;

添加类库CSQLiteHelper,用于存放SQLite操作方法(此代码原文链接. https://blog.csdn.net/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_SQLite
 12 {
 13     public class CSQLiteHelper
 14     {
 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 SQLiteConnString
 23         {
 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             try
 42             {
 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                 cmd.CommandText = "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             try
 79             {
 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             try
 98             {
 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                     this.Commit();
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                 this._SQLiteTrans.Commit();
156                 this._IsRunTrans = false;
157             }
158         }
159 
160         
161     }
162 }
View Code

 

 

 此时运行会报错,

警告  所生成项目的处理器架构“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             try
 9             {
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                 cmd.CommandText = "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 Program
 2     {
 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 {
 3     CSQLiteHelper sqlHelper = new CSQLiteHelper(dbPath);
 4     sqlHelper.OpenDbConn();
 5     string commandStr = "insert into Stars(Name,Team,Number) values(@name,@team,@number)";
 6     foreach (var item in stars)
 7     {
 8         if (isExist("Name", item[0].ToString()))
 9         {
10             Console.WriteLine(item[0] + "的数据已存在!");
11             continue;
12         }
13         else
14         {
15             sqlHelper.ExecuteNonQuery(commandStr, item);
16             Console.WriteLine(item[0] + "的数据已保存!");
17             Console.ReadKey();
18         }
19     }
20     sqlHelper.CloseDbConn();
21     Console.ReadKey();
22             
23 }

 

效果如下:

 


 

五、查询数据

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

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

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

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

 

 

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

 

效果如下

 


 

 六、删除数据

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

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

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

"delete * from Stars where [condition];

 调用一下

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

删除前:

删除后:

 

 

 

 

 

 

欢迎留言区讨论,如果有帮助,就顶一下吧~

 

 

 


 

欢迎打赏

 

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网