PC软件开发技术之三:C#操作SQLite数据库
我们在开发应用是经常会需要用到一些数据的存储,存储的方式有多种,使用数据库是一种比较受大家欢迎的方式。但是对于一些小型的应用,如一些移动APP,通常的数据库过于庞大,而轻便的SQLite则能解决这一问题。不但操作方便,而且只需要要一个文件即可,在这里我们来说一说使用C#语言操作SQLite数据库。
1、SQLite简介
SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。它是D.RichardHipp建立的公有领域项目。它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口,同样比起MySQL、PostgreSQL这两款开源的世界著名数据库管理系统来讲,它的处理速度比他们都快。
如果想了解更多关于SQLite的问题,可以访问它的官方网站:http://www.sqlite.org/
2、开始前的准备
在开始之前我们需要准备必要的开发环境,这次咱们使用的是Visual Studio 2015开发环境,但是我们开发基于SQLite的应用光有VS2015还不够。我需要到SQLite的官方网站下载并安装SQLite。
在SQLite官网找到下载,有应用于各种环境的SQLite组件及源码,我们选择Precompiled Binaries for .NET,这是应用于.NET开发环境的,点击进入会看到应用于.NET2.0直至4.6以及32位和64位平台的各个版本。我们选择Setups for 32-bit Windows (.NET Framework 4.6)下载安装即可。
3、C#操作SQLite的封装
在完成开发环境的准备之后,我们接下来实现对SQLite操作的必要封装,以进一步降低在具体应用中的使用难度。在这里我们只是封装一些常用而且必要的功能。
public class SQLiteHelper
{
//创建数据库文件
public static void CreateDBFile(string fileName)
{
string path = System.Environment.CurrentDirectory + @"/Data/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string databaseFileName = path + fileName;
if (!File.Exists(databaseFileName))
{
SQLiteConnection.CreateFile(databaseFileName);
}
}
//生成连接字符串
private static string CreateConnectionString()
{
SQLiteConnectionStringBuilder connectionString = new SQLiteConnectionStringBuilder();
connectionString.DataSource = @"data/ScriptHelper.db";
string conStr = connectionString.ToString();
return conStr;
}
/// <summary>
/// 对插入到数据库中的空值进行处理
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static object ToDbValue(object value)
{
if (value == null)
{
return DBNull.Value;
}
else
{
return value;
}
}
/// <summary>
/// 对从数据库中读取的空值进行处理
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static object FromDbValue(object value)
{
if (value == DBNull.Value)
{
return null;
}
else
{
return value;
}
}
/// <summary>
/// 执行非查询的数据库操作
/// </summary>
/// <param name="sqlString">要执行的sql语句</param>
/// <param name="parameters">参数列表</param>
/// <returns>返回受影响的条数</returns>
public static int ExecuteNonQuery(string sqlString, params SQLiteParameter[] parameters)
{
string connectionString=CreateConnectionString();
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
conn.Open();
using (SQLiteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sqlString;
foreach (SQLiteParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
return cmd.ExecuteNonQuery();
}
}
}
/// <summary>
/// 执行查询并返回查询结果第一行第一列
/// </summary>
/// <param name="sqlString">SQL语句</param>
/// <param name="sqlparams">参数列表</param>
/// <returns></returns>
public static object ExecuteScalar(string sqlString, params SQLiteParameter[] parameters)
{
string connectionString = CreateConnectionString();
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
conn.Open();
using (SQLiteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sqlString;
foreach (SQLiteParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
return cmd.ExecuteScalar();
}
}
}
/// <summary>
/// 查询多条数据
/// </summary>
/// <param name="sqlString">SQL语句</param>
/// <param name="parameters">参数列表</param>
/// <returns>返回查询的数据表</returns>
public static DataTable GetDataTable(string sqlString,params SQLiteParameter[] parameters)
{
string connectionString = CreateConnectionString();
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
conn.Open();
using (SQLiteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sqlString;
foreach (SQLiteParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
DataSet ds = new DataSet();
SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd);
adapter.Fill(ds);
return ds.Tables[0];
}
}
}
}
4、应用实例
上面封装完了之后,我们就是使用上面封装的函数来实际操作SQLite数据库。对数据库的应用实例无非就是对各种对象的增、删、改、查。我没列举一个对源码类型对象的各种操作实例如下:
public class ScriptTypeDAL
{
public ScriptTypeM ToScriptType(DataRow row)
{
ScriptTypeM type = new ScriptTypeM();
type.ScriptTypeId = (Guid)row["ScriptTypeId"];
type.ScriptType = (string)row["ScriptType"];
type.IsUsing = (bool)row["IsUsing"];
return type;
}
public void Insert(ScriptTypeM Type)
{
SQLiteHelper.ExecuteNonQuery(@"insert into TB_ScriptType(ScriptTypeId,ScriptType,IsUsing)
Values(@ScriptTypeId,@ScriptType,1)",
new SQLiteParameter("ScriptTypeId", Type.ScriptTypeId),
new SQLiteParameter("ScriptType", Type.ScriptType));
}
public void Update(ScriptTypeM Type)
{
SQLiteHelper.ExecuteNonQuery(@"update TB_ScriptType set ScriptType=@ScriptType,
IsUsing=@IsUsing where ScriptTypeId=@ScriptTypeId",
new SQLiteParameter("ScriptType", Type.ScriptType),
new SQLiteParameter("IsUsing", Type.IsUsing),
new SQLiteParameter("ScriptTypeId", Type.ScriptTypeId));
}
public ScriptTypeM GetbyId(Guid id)
{
DataTable table = SQLiteHelper.GetDataTable("select * from TB_ScriptType where ScriptTypeId=@id",
new SQLiteParameter("id", id));
if (table.Rows.Count <= 0)
{
return null;
}
else if (table.Rows.Count > 1)
{
throw new Exception("Id重复!");
}
else
{
return ToScriptType(table.Rows[0]);
}
}
public ScriptTypeM GetbyName(string name)
{
DataTable table = SQLiteHelper.GetDataTable("select * from TB_ScriptType where ScriptType=@name",
new SQLiteParameter("name", name));
if (table.Rows.Count <= 0)
{
return null;
}
else if (table.Rows.Count > 1)
{
throw new Exception("类型名称重复!");
}
else
{
return ToScriptType(table.Rows[0]);
}
}
public ScriptTypeM[] ListAll()
{
DataTable table = SQLiteHelper.GetDataTable("select * from TB_ScriptType where IsUsing=1");
ScriptTypeM[] type = new ScriptTypeM[table.Rows.Count];
for (int i = 0; i < table.Rows.Count; i++)
{
type[i] = ToScriptType(table.Rows[i]);
}
return type;
}
public ScriptTypeM[] Search(string sql, List<SQLiteParameter> parameterList)
{
DataTable table = SQLiteHelper.GetDataTable(sql, parameterList.ToArray());
ScriptTypeM[] type = new ScriptTypeM[table.Rows.Count];
for (int i = 0; i < table.Rows.Count; i++)
{
type[i] = ToScriptType(table.Rows[i]);
}
return type;
}
}
SQLite数据库小巧而且应用方便,在一些小型应用和嵌入式应用中很有优势,当然如何应用的得心应手就看个人了。
欢迎关注:
阅读更多
- C#软件开发实例.私人订制自己的屏幕截图工具(八)添加键盘操作截图的功能
- 从C#到Objective-C,循序渐进学习苹果开发(7)--使用FMDB对Sqlite数据库进行操作
- 想带几个徒弟,C#.NET开发技术方面的,把自己积累的软件技术传授给高徒[非网络带人]
- Qt软件开发之sqlite数据库操作
- 京东价格监控软件开发技术探讨九:C#判断京东登录是否需要验证码
- 京东价格监控软件开发技术探讨一:C#实现获取京东商品信息(价格、库存)
- 想带几个徒弟,C#.NET开发技术方面的,把自己积累的软件技术传授给高徒[非网络带人]
- C#软件开发实例.私人订制自己的屏幕截图工具(八)添加键盘操作截图的功能
- C#转换为VB.NET(转自李洪根的blog-专注软件开发技术)
- 想带几个徒弟,C#.NET开发技术方面的,把自己积累的软件技术传授给高徒[非网络带人]
- 京东价格监控软件开发技术探讨三:使用C#模拟京东登录
- [毕业生的商业软件开发之路]C#进阶建议 推荐
- c# 注册表操作,用于更新软件
- 【C#】开发可以可视化操作的windows服务
- c#小软件(SaveClassic)开发手记--(3)基础类(文件操作类FileOption)
- 软件开发与数学基础 一个C#中的例子——lambda表达式
- [转发]在Visual Studio 2010/2012/2013/2015上使用C#开发Android/IOS安装包和操作步骤
- [自娱自乐] 4、超声波测距模块DIY笔记(四)——终结篇·基于C#上位机软件开发
- C#软件开发实例.私人订制自己的屏幕截图工具(七)添加放大镜的功能
- “消费返利系统”技术开发软件