C# SQLite 数据库

数据库

Oracle。Oracle的应用,主要在传统行业的数据化业务中,比如:银行、金融这样的对可用性、健壮性、安全性、实时性要求极高的业务

MS SQL Server。windows生态系统的产品,好处坏处都很分明。好处就是,高度集成化,微软也提供了整套的软件方案,基本上一套win系统装下来就齐活了。因此,不那么缺钱,但很缺IT人才的中小企业,会偏爱 MS SQL Server 。例如,自建ERP系统、商业智能、垂直领域零售商、餐饮、事业单位等等。

MySQL。MySQL基本是生于互联网,长于互联网。其应用实例也大都集中于互联网方向

SQLite介绍

SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。

它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 C#、PHP、Java等,还有ODBC接口。SQLite第一个Alpha版本诞生于2000年5月。 至2015年已经有15个年头。

Windows平台使用

1、在Assets目录下创建Plugins目录,将Mono.Data.Sqlite.dll、System.Data.dll、sqlite3.dll三个文件放到工程Plugins目录下。

2、在Assets目录下创建StreamingAssets目录,把db放在该目录内。

3、将DbAccess.cs脚本添加到工程中

Android平台使用

1、在Assets目录下创建Plugins目录,将Mono.Data.Sqlite.dll、System.Data.dll、sqlite3.dll三个文件放到工程Plugins目录下。

2、然后在Plugins目录下建立Android目录,再将libsqlite3.so放到Android目录下。

3、在Assets目录下创建StreamingAssets目录,把db放在该目录内。 4、将DbAccess.cs脚本添加到工程中。

 

 SQLite的数据库常规操作封装的通用类

  1 using UnityEngine;
  2 using System;
  3 using System.Collections;
  4 using Mono.Data.Sqlite;
  5 /// <summary>
  6 /// SQLite数据库操作类
  7 /// </summary>
  8 public class DbAccess
  9 {
 10     private SqliteConnection conn; // SQLite连接
 11     private SqliteCommand cmd; // SQLite命令
 12     private SqliteDataReader reader;
 13     public DbAccess (string connectionString)    
 14     {
 15         OpenDB (connectionString);
 16     }
 17     public DbAccess (){ }
 18     /// <summary>
 19     /// 打开数据库
 20     /// </summary>
 21     /// <param name="connectionString"></param>
 22     public void OpenDB (string connectionString)        
 23     {
 24         try
 25         {
 26             conn = new SqliteConnection (connectionString);            
 27             conn.Open ();            
 28             Debug.Log ("Connected to db,连接数据库成功!");
 29         }
 30         catch(Exception e)
 31         {
 32             string temp1 = e.ToString();
 33             Debug.Log(temp1);
 34         }        
 35     }
 36     /// <summary>
 37     /// 关闭数据库连接
 38     /// </summary>
 39     public void CloseSqlConnection ()    
 40     {
 41         if (cmd != null) { cmd.Dispose (); cmd = null; }                        
 42         if (reader != null) { reader.Dispose (); reader = null;}                    
 43         if (conn != null) {    conn.Close (); conn = null;}            
 44         Debug.Log ("Disconnected from db.关闭数据库!");    
 45     }    
 46     /// <summary>
 47     /// 执行SQL语句
 48     /// </summary>
 49     /// <param name="sqlQuery"></param>
 50     /// <returns></returns>
 51     public SqliteDataReader ExecuteQuery ( string sqlQuery )        
 52     {
 53         Debug.Log( "ExecuteQuery:: " + sqlQuery );
 54         cmd = conn.CreateCommand ();
 55         cmd.CommandText = sqlQuery;
 56         reader = cmd.ExecuteReader ();
 57         return reader;
 58     }
 59     
 60     /// <summary>
 61     /// 查询表中全部数据 param tableName=表名 
 62     /// </summary>
 63     public SqliteDataReader ReadFullTable (string tableName)        
 64     {
 65         string query = "SELECT * FROM " + tableName;
 66         return ExecuteQuery (query);
 67     }
 68     /// <summary>
 69     /// 插入数据 param tableName=表名 values=插入数据内容
 70     /// </summary>
 71     public SqliteDataReader InsertInto (string tableName, string[] values)        
 72     {
 73         string query = "INSERT INTO " + tableName + " VALUES (" + values[0];
 74         for (int i = 1; i < values.Length; ++i) {    
 75             query += ", " + values[i];    
 76         }
 77         query += ")";
 78         return ExecuteQuery (query);
 79     }    
 80     /// <summary>
 81     /// 更新数据 param tableName=表名 cols=更新字段 colsvalues=更新内容 selectkey=查找字段(主键) selectvalue=查找内容
 82     /// </summary>
 83     public SqliteDataReader UpdateInto (string tableName, string []cols,string []colsvalues,string selectkey,string selectvalue)
 84     {
 85         string query = "UPDATE "+tableName+" SET "+cols[0]+" = "+colsvalues[0];
 86         for (int i = 1; i < colsvalues.Length; ++i) {
 87             query += ", " +cols[i]+" ="+ colsvalues[i];
 88         }        
 89         query += " WHERE "+selectkey+" = "+selectvalue+" ";        
 90         return ExecuteQuery (query);
 91     }
 92     
 93     /// <summary>
 94     /// 删除数据 param tableName=表名 cols=字段 colsvalues=内容
 95     /// </summary>
 96     public SqliteDataReader Delete(string tableName,string []cols,string []colsvalues)
 97     {
 98         string query = "DELETE FROM "+tableName + " WHERE " +cols[0] +" = " + colsvalues[0];        
 99         for (int i = 1; i < colsvalues.Length; ++i) {            
100             query += " or " +cols[i]+" = "+ colsvalues[i];
101         }
102         return ExecuteQuery (query);
103     }    
104     /// <summary>
105     /// 插入数据 param tableName=表名 cols=插入字段 value=插入内容
106     /// </summary>
107     public SqliteDataReader InsertIntoSpecific (string tableName, string[] cols, string[] values)        
108     {
109         if (cols.Length != values.Length) {    
110             throw new SqliteException ("columns.Length != values.Length");
111         }
112         string query = "INSERT INTO " + tableName + "(" + cols[0];
113         for (int i = 1; i < cols.Length; ++i) {    
114             query += ", " + cols[i];    
115         }
116         query += ") VALUES (" + values[0];
117         for (int i = 1; i < values.Length; ++i) {    
118             query += ", " + values[i];    
119         }        
120         query += ")";        
121         return ExecuteQuery (query);        
122     }
123     /// <summary>
124     /// 删除表中全部数据
125     /// </summary>
126     public SqliteDataReader DeleteContents (string tableName)        
127     {    
128         string query = "DELETE FROM " + tableName;
129         return ExecuteQuery (query);
130     }
131     /// <summary>
132     /// 创建表 param name=表名 col=字段名 colType=字段类型
133     /// </summary>
134     public SqliteDataReader CreateTable (string name, string[] col, string[] colType)
135     {
136         if (col.Length != colType.Length) {
137             throw new SqliteException ("columns.Length != colType.Length");
138         }
139         string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];        
140         for (int i = 1; i < col.Length; ++i) {    
141             query += ", " + col[i] + " " + colType[i];    
142         }
143         query += ")";        
144         return ExecuteQuery (query);        
145     }
146     /// <summary>
147     /// 按条件查询数据 param tableName=表名 items=查询字段 col=查找字段 operation=运算符 values=内容
148     /// </summary>
149     public SqliteDataReader SelectWhere (string tableName, string[] items, string[] col, string[] operation, string[] values)    
150     {    
151         if (col.Length != operation.Length || operation.Length != values.Length) {    
152             throw new SqliteException ("col.Length != operation.Length != values.Length");    
153         }
154         string query = "SELECT " + items[0];
155         for (int i = 1; i < items.Length; ++i) {    
156             query += ", " + items[i];
157         }
158         query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";
159         for (int i = 1; i < col.Length; ++i) {
160             query += " AND " + col[i] + operation[i] + "'" + values[i] + "' ";
161         }
162         return ExecuteQuery (query);
163     }
164     /// <summary>
165     /// 查询表
166     /// </summary>
167     public SqliteDataReader Select(string tableName, string col, string values)
168     {
169         string query = "SELECT * FROM " + tableName  + " WHERE " + col + " = " + values;
170         return ExecuteQuery (query);
171     }
172     public SqliteDataReader Select(string tableName, string col,string operation, string values)
173     {
174         string query = "SELECT * FROM " + tableName  + " WHERE " + col + operation + values;
175         return ExecuteQuery (query);
176     }
177     /// <summary>
178     /// 升序查询
179     /// </summary>
180     public SqliteDataReader SelectOrderASC (string tableName,string col)
181     {
182         string query = "SELECT * FROM " + tableName  + " ORDER BY " + col + " ASC";
183         return ExecuteQuery (query);
184     }
185     /// <summary>
186     /// 降序查询
187     /// </summary>
188     public SqliteDataReader SelectOrderDESC (string tableName,string col)
189     {
190         string query = "SELECT * FROM " + tableName  + " ORDER BY " + col + " DESC";
191         return ExecuteQuery (query);
192     }
193     /// <summary>
194     /// 查询表行数
195     /// </summary>
196     public SqliteDataReader SelectCount(string tableName)
197     {
198         string query = "SELECT COUNT(*) FROM " + tableName;
199         return ExecuteQuery (query);
200     }
201 }
DbAccess

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 using Mono .Data .Sqlite;
 5 
 6 namespace ns
 7 {
 8     /// <summary>
 9     ///  打开和关闭数据库
10     /// </summary>
11     public class SQLiteHelper : MonoBehaviour 
12     {
13         protected string dbName = "test2.db"; // 文件名
14         private string filePath // 文件路径
15         {
16             get { return Application .streamingAssetsPath + "/" + dbName; }
17         }
18 
19         protected DbAccess db; // dbAccess实例
20         protected SqliteDataReader reader;// 
21         /// <summary>
22         /// 打开数据库
23         /// </summary>
24         protected void OpenDB()
25         {
26             db = new DbAccess( "URI=file:" + filePath );
27         }
28         /// <summary>
29         /// 关闭数据库
30         /// </summary>
31         protected void CloseDB()
32         {
33             if( reader != null )
34             {
35                 reader .Close();
36                 reader = null;
37             }
38             
39             db .CloseSqlConnection();
40         }
41         /// <summary>
42         /// 对象前后添加单引号
43         /// </summary>
44         /// <param name="o"></param>
45         /// <returns></returns>
46         protected string GetStr( object o )
47         {
48             return "'" + o + "'";
49         }
50 
51     }
52 }
SQLiteHelper

  1 using System.Collections;
  2 using System.Collections.Generic;
  3 using UnityEngine;
  4 using ns;
  5 
  6 public class MySQLiteDemo : MySQLiteHelper
  7 {
  8     /// <summary>
  9     /// 创建表
 10     /// </summary>
 11     private void CreateTable()
 12     {
 13         //打开数据库
 14         OpenDB();
 15 
 16         db.CreateTable("MyRole", new string[] { "id", "name", "age", "lv", "exp" },
 17             new string[] { "int", "text", "int", "int", "float" });
 18         //关闭数据库
 19         CloseDB();
 20     }
 21 
 22 
 23     /// <summary>
 24     /// 插入数据
 25     /// </summary>
 26     private void InsertData()
 27     {
 28         //打开数据库
 29         OpenDB();
 30         //插入数据库
 31         db.InsertInto
 32             ("MyRole", new string[] { GetStr("1"), GetStr("张三"), GetStr("100"), GetStr("12"), GetStr("120") });
 33         db.InsertInto
 34             ("MyRole", new string[] { GetStr("2"), GetStr("李四"), GetStr("110"), GetStr("13"), GetStr("130") });
 35         db.InsertInto
 36             ("MyRole", new string[] { GetStr("3"), GetStr("王五"), GetStr("120"), GetStr("14"), GetStr("140") });
 37         db.InsertInto
 38             ("MyRole", new string[] { GetStr("4"), GetStr("赵六"), GetStr("130"), GetStr("15"), GetStr("150") });
 39 
 40         //关闭数据库
 41         CloseDB();
 42     }
 43 
 44     /// <summary>
 45     /// 删除数据库
 46     /// </summary>
 47     private void DeleteData()
 48     {
 49         //打开数据库
 50         OpenDB();
 51         // 删除数据: 多个条件直接是或的关系
 52         // DELETE FROM Role WHERE id = 1 or lv = 13
 53 
 54         //db.Delete("MyRole",
 55         //    new string[] { "id", "lv" },
 56         //    new string[] { "1", "130" }
 57         //    );
 58         db.DeleteContents("MyRole");
 59         //关闭数据库
 60 
 61         CloseDB();
 62     }
 63     /// <summary>
 64     /// 更新数据
 65     /// </summary>
 66     private void UpdateData()
 67     {
 68         //打开数据库
 69         OpenDB();
 70         // 更新数据: id为1数据 exp改为350 lv改为16
 71         // UPDATE Role SET exp = 350, lv =16 WHERE id = 1 
 72         db.UpdateInto("MyRole", 
 73             new string[] { "exp", "lv" }, new string[] { "350", "16", }, "id", "1");
 74         //关闭数据库
 75         CloseDB();
 76     }
 77     // 查找数据
 78     private void SearchData()
 79     {
 80         OpenDB();
 81         // 查询 查找id为3 lv为21的数据
 82         // 找到 name 和 age
 83         // 多个条件之间是与的关系
 84         // SELECT name, age FROM Role WHERE id='3'  AND lv='14'
 85         reader = db.SelectWhere("MyRole",
 86             new string[] { "name", "age" },
 87             new string[] { "id", "lv" },
 88             new string[] { "=", "=" },
 89             new string[] { "1", "14" }
 90             );
 91         if (reader.HasRows)
 92         {
 93             reader.Read();
 94             print(reader.GetString(reader.GetOrdinal("name")));
 95             print(reader.GetInt32(reader.GetOrdinal("age")));
 96         }
 97 
 98         CloseDB();
 99     }
100 
101     /// <summary>
102     /// 查找多个数据
103     /// </summary>
104     private void SelectData()
105     {
106        // 打开数据库
107             OpenDB();
108 
109             //reader = db .Select( "Role" , "id" , "2" );// 查询所有id 为 2的数据
110             //reader = db .Select( "Role" , "id" , ">" , "1" ); // 查询所有id>1的数据
111             //reader = db .ReadFullTable("Role"); // 读取整张表 
112             //reader = db .SelectOrderASC( "Role" , "age" ); // age从小到大排列
113             reader = db .SelectOrderDESC( "MyRole" , "lv" ); //  lv从大到小
114             if ( reader.HasRows )
115             {
116                 while( reader .Read() )
117                 {
118                     string s = "";
119                     s += reader .GetInt32( reader .GetOrdinal( "id" ) ) + " , " ;
120                     s += reader .GetString( reader .GetOrdinal( "name" ) ) + " , ";
121                     s += reader .GetInt32( reader .GetOrdinal( "age" ) ) + " , ";
122                     s += reader .GetInt32( reader .GetOrdinal( "lv" ) ) + " , ";
123                     s += reader .GetFloat( reader .GetOrdinal( "exp" ) );
124                     print( s );
125                 }
126             }
127             // 关闭数据库
128             CloseDB();
129     }
130 
131     private void OnGUI()
132     {
133         if (GUILayout.Button("创建MyRole表"))
134         {
135             CreateTable();
136         }
137         if (GUILayout.Button("插入数据"))
138         {
139             InsertData();
140         }
141         if (GUILayout.Button("删除数据库"))
142         {
143             DeleteData();
144         }
145         if (GUILayout.Button("更新数据"))
146         {
147             UpdateData();
148         }
149         if (GUILayout.Button("查询数据"))
150         {
151             SearchData();
152         }
153         if (GUILayout.Button("多条数据查询"))
154         {
155             SelectData();
156         }
157     }
158 
159 
160 }
MySQLiteDemo

 

原文地址:https://www.cnblogs.com/ASsss/p/10512972.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


SQLite架构简单,又有Json计算能力,有时会承担Json文件/RESTful的计算功能,但SQLite不能直接解析Json文件/RESTful,需要用Java代码硬写,或借助第三方类库,最后再拼成insert语句插入数据表,代码非常繁琐,这里就不展示了。参考前面的代码可知,入库的过程比较麻烦,不能只用SQL,还要借助Java或命令行。SPL是现代的数据计算语言,属于简化的面向对象的语言风格,有对象的概念,可以用点号访问属性并进行多步骤计算,但没有继承重载这些内容,不算彻底的面向对象语言。...
使用Python操作内置数据库SQLite以及MySQL数据库。
破解微信数据库密码,用python导出微信聊天记录
(Unity)SQLite 是一个软件库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。SQLite 是在世界上最广泛部署的 SQL 数据库引擎。SQLite 源代码不受版权限制。本教程将告诉您如何使用 SQLite 编程,并让你迅速上手。.................................
安卓开发,利用SQLite实现登陆注册功能
相比大多数数据库而言,具有等优势,广泛应用于、等领域。
有时候,一个项目只有一个数据库,比如只有SQLite,或者MySQL数据库,那么我们只需要使用一个固定的数据库即可。但是一个项目如果写好了,有多个用户使用,但是多个用户使用不同的数据库,这个时候,我们就需要把软件设计成可以连接多个数据库的模式,用什么数据库,就配置什么数据库即可。4.Users实体类,这个实体类要和数据库一样的,形成一一对应的关系。11.Sqlite数据库,需要在代码里面创建数据库,建立表,再建立数据。8.我们开启MySQL数据库,然后进行调试,看程序的结果。2.安装SqlSugar。
基于Android的背单词软件,功能强大完整。
SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统。说白了就是使用起来轻便简单,
Android的简单购物车案例
SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。它是D.RichardHipp建立的公有领域项目。它的设计目标是嵌入式的,而且已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源的世界著名数据库...
Qt设计较为美观好看的登录注册界面(包含SQLite数据库以及TCP通信的应用)
SQLite是用C语言开发的跨平台小型数据库,可嵌入其他开发语言,也可在单机执行。SPL是用Java开发的跨平台的数据计算语言,可嵌入Java,可在单机执行,可以数据计算服务的形式被远程调用。两者的代码都是解释执行的。...
新建库.openDATA_BASE;新建表createtableLIST_NAME(DATA);语法:NAME关键字...<用逗号分割>删除表droptableNAME;查看表.schema查看表信息新建数据insertintoLIST_NAMEvalues();语法:CLASS,PARAMETER...,CLASS是类别,PARAMETER是参数<用逗号分割新建的
importsqlite3classDemo01:def__init__(self):self.conn=sqlite3.connect("sql_demo_001.db")self.cursor1=self.conn.cursor()self.cursor1.execute("select*fromtable_001wherename=?andid=?",('ssss&#0
 在客户端配置文件<configuration>节点下,添加:<connectionStrings>      <add name="localdb" connectionString="Data Source=config/local.db;Version=3;UseUTF16Encoding=True;" providerName="System.Data.SQLite.SQLiteFactory"/&g
提到锁就不得不说到死锁的问题,而SQLite也可能出现死锁。下面举个例子:连接1:BEGIN(UNLOCKED)连接1:SELECT...(SHARED)连接1:INSERT...(RESERVED)连接2:BEGIN(UNLOCKED)连接2:SELECT...(SHARED)连接1:COMMIT(PENDING,尝试获取EXCLUSIVE锁,但还有SHARED锁未释放,返回SQLITE_BUSY)连接2:INSERT...
SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在iOS和Android的App中都可以集成。Python就内置了SQLite3,所以,在Python中使用SQLite,不需要安装任何东西,直接使用。在使用SQLite前,我们先要搞清楚几个概念:表
设计思想————首先要确定有几个页面、和每个页面的大致布局由于是入门,我也是学习了不是很长的时间,所以项目比较low。。。。第一个页面,也就是打开APP的首页面:今天这个博客,先实现添加功能!:首先对主界面进行布局:其中activity_main.xml的代码为<?xmlversion="1.0"encoding="