前言
我们在开发应用是经常会需要用到一些数据的存储,存储的方式有多种,使用数据库是一种比较受大家欢迎的方式。但是对于一些小型的应用,如一些移动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类库
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. 判断数据文件是否存在
/// <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. 判断表是否存在
/// <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. 查询
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. 新增/修改
//存在更新,不存在插入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. 删除
//删除记录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;}
四、参考文章
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对VEVB武林网的支持。
注:相关教程知识阅读请移步到c#教程频道。