C#操作SQLite⽅法实例详解本⽂实例讲述了C#操作SQLite⽅法。分享给⼤家供⼤家参考。具体分析如下:
地址:
System.Data.Sqlite⼊⼿。。。
⾸先import/using:
复制代码代码如下:
using System.Data.SQLite;
Connection和Command:
private SQLiteConnection conn;
private SQLiteCommand cmd;
连接db:
conn = new SQLiteConnection("Data Source=c:\\test.db");
conn.Open();
INSERT/UPDATE:
cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO user(email,name) VALUES ('email','name')";
cmd.ExecuteNonQuery();
cmd.CommandText = "UPDATE userSET name = 'Codelicious' WHERE ID = 1";
cmd.ExecuteNonQuery();
SELECT:
cmd.CommandText = "SELECT ID, name FROM user";
SQLiteDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("ID: " + reader.GetInt16(0));
Console.WriteLine("name: " + reader.GetString(1));
}
}
模板程序:
using System;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;
namespace SQLiteQueryBrowser
{
/// <summary>
/// 说明:这是⼀个针对System.Data.SQLite的数据库常规操作封装的通⽤类。
/// </summary>
public class SQLiteDBHelper
{
private string connectionString = string.Empty;
/// <summary>
/// 构造函数
/
// </summary>
/// <param name="dbPath">SQLite数据库⽂件路径</param>
public SQLiteDBHelper(string dbPath)
{
public static void CreateDB(string dbPath)
{
using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + dbPath))
{
connection.Open();
using (SQLiteCommand command = new SQLiteCommand(connection))
{
command.CommandText = "CREATE TABLE Demo(id integer NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE)";
command.ExecuteNonQuery();
command.CommandText = "DROP TABLE Demo";
command.ExecuteNonQuery();
}
}
}
/// <summary>
/// 对SQLite数据库执⾏增删改操作,返回受影响的⾏数。
/// </summary>
/// <param name="sql">要执⾏的增删改的SQL语句</param>
/// <param name="parameters">执⾏增删改语句所需要的参数,参数必须以它们在SQL语句中的顺序为准</param>
/// <returns></returns>
public int ExecuteNonQuery(string sql, SQLiteParameter[] parameters)
{
int affectedRows = 0;
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
using (DbTransaction transaction = connection.BeginTransaction())
{
using (SQLiteCommand command = new SQLiteCommand(connection))
{
command.CommandText = sql;
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
affectedRows = command.ExecuteNonQuery();
}
transaction.Commit();
}
}
return affectedRows;
}
/// <summary>
/// 执⾏⼀个查询语句,返回⼀个关联的SQLiteDataReader实例
/// </summary>
/
// <param name="sql">要执⾏的查询语句</param>
/// <param name="parameters">执⾏SQL查询语句所需要的参数,参数必须以它们在SQL语句中的顺序为准</param>      /// <returns></returns>
public SQLiteDataReader ExecuteReader(string sql, SQLiteParameter[] parameters)
{
SQLiteConnection connection = new SQLiteConnection(connectionString);
SQLiteCommand command = new SQLiteCommand(sql, connection);
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
connection.Open();
return command.ExecuteReader(CommandBehavior.CloseConnection);
}
/// <summary>
/// 执⾏⼀个查询语句,返回⼀个包含查询结果的DataTable
/// </summary>
/// <param name="sql">要执⾏的查询语句</param>
/// <param name="parameters">执⾏SQL查询语句所需要的参数,参数必须以它们在SQL语句中的顺序为准</param>      /// <returns></returns>
public DataTable ExecuteDataTable(string sql, SQLiteParameter[] parameters)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
DataTable data = new DataTable();
adapter.Fill(data);
return data;
}
}
}
/// <summary>
/// 执⾏⼀个查询语句,返回查询结果的第⼀⾏第⼀列
/// </summary>
/// <param name="sql">要执⾏的查询语句</param>
/// <param name="parameters">执⾏SQL查询语句所需要的参数,参数必须以它们在SQL语句中的顺序为准</param>      /// <returns></returns>
public Object ExecuteScalar(string sql, SQLiteParameter[] parameters)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
DataTable data = new DataTable();
adapter.Fill(data);
return data;
}
}
}
/// <summary>
/// 查询数据库中的所有数据类型信息
/// </summary>
/// <returns></returns>
public DataTable GetSchema()
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
DataTable data=connection.GetSchema("TABLES");
connection.Close();
//foreach (DataColumn column in data.Columns)
//{
//  Console.WriteLine(column.ColumnName);
//}
return data;
}
}
}
}
完整的程序例⼦:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;
writeline方法属于类
using SQLiteQueryBrowser;
namespace SQLiteDemo
{
class Program
{
static void Main(string[] args)
{
//CreateTable();
//InsertData();
ShowData();
Console.ReadLine();
}
public static void CreateTable()
{
string dbPath = "D:\\Demo.db3";
/
/如果不存在改数据库⽂件,则创建该数据库⽂件
if (!System.IO.File.Exists(dbPath))
{
SQLiteDBHelper.CreateDB("D:\\Demo.db3");
}
SQLiteDBHelper db = new SQLiteDBHelper("D:\\Demo.db3");
string sql = "CREATE TABLE Test3(id integer NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,Name char(3),TypeName varchar(50),addDate datetime,UpdateTime Date,Time time,Comments blob)";        db.ExecuteNonQuery(sql, null);
}
public static void InsertData()
{
string sql = "INSERT INTO Test3(Name,TypeName,addDate,UpdateTime,Time,Comments)values(@Name,@TypeName,@addDate,@UpdateTime,@Time,@Comments)";
SQLiteDBHelper db = new SQLiteDBHelper("D:\\Demo.db3");
for (char c = "A"; c <= "Z"; c++)
{
for (int i = 0; i < 100; i++)
{
SQLiteParameter[] parameters = new SQLiteParameter[]{
new SQLiteParameter("@Name",c+i.ToString()),
new SQLiteParameter("@TypeName",c.ToString()),
new SQLiteParameter("@addDate",DateTime.Now),
new SQLiteParameter("@UpdateTime",DateTime.Now.Date),
new SQLiteParameter("@Time",DateTime.Now.ToShortTimeString()),
new SQLiteParameter("@Comments","Just a Test"+i)
};
db.ExecuteNonQuery(sql, parameters);
}
}
}
public static void ShowData()
{
//查询从50条起的20条记录
string sql = "select * from test3 order by id desc limit 50 offset 20";
SQLiteDBHelper db = new SQLiteDBHelper("D:\\Demo.db3");
using (SQLiteDataReader reader = db.ExecuteReader(sql, null))
{
while (reader.Read())
{
Console.WriteLine("ID:{0},TypeName{1}", reader.GetInt64(0), reader.GetString(1));
}
}
}
}
}
在实际情况中,采⽤通⽤类⼤批量插⼊数据会有些慢,这是因为在System.Data.SQLite中的操作如果没有指定操作,则会被当做⼀个事物,如果需要⼀次性写⼊⼤量记录,则建议显式创建⼀个事物,在这个事务中完成所有的操作⽐较好,这样的话⽐每次操作创建⼀个事物的效率要提升很多。
最终利⽤VS2008提供的功能,可以看到⾥⾯的数据如下:
需要说明的是在System.Data.SQLite中数据类型的规定不适很严格,从创建Test3表的SQL语句来看,表中addDate、UpdateTime、Time分别是DateTime、Date、Time类型字段,但实际上我们插⼊的时候没有按照这个规定,最终显⽰的结果也是尽量遵循数据库字段的定义。
总结
System.Data.SQLite确实是⼀个⾮常⼩巧精悍的数据库,作为对SQLite的封装(SQLite可以在Android等类型的⼿机上利⽤Java访问),它依然是体较⼩,同⽐性能⾼、内存消耗⼩、⽆需安装仅需⼀个dll就可以运⾏的优点(如果在Mobile⼿机上则需要两个⽂件),唯⼀的⼀个缺点是没有⽐较的GUI(图形⽤户界⾯),不过正因为如此它才得以体积⼩。
在实际开发中没有图形⽤户界⾯可能有些不便,我们可以使⽤VS来查看和操作数据,我⾃⼰也做了⼀个⼩东东,便于管理和维护数据,界⾯如下:
如果你要开发数据量在10万条以下的应⽤,我建议你尝试使⽤⼀下System.Data.SQLite,它或许是⼀个不错的选择。
public static void CreateTable()
{
string dbPath = "D:\\Demo.db3";
//如果不存在改数据库⽂件,则创建该数据库⽂件
if (!System.IO.File.Exists(dbPath))
{
SQLiteDBHelper.CreateDB("D:\\Demo.db3");
}
SQLiteDBHelper db = new SQLiteDBHelper("D:\\Demo.db3");
string sql = "CREATE TABLE Test3(id integer NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,Name char(3),TypeName varchar(50),addDate datetime,UpdateTime Date,Time time,Comments blob)";
db.ExecuteNonQuery(sql, null);
}
public static void InsertData()
{
string sql = "INSERT INTO Test3(Name,TypeName,addDate,UpdateTime,Time,Comments)values(@Name,@TypeName,@addDate,@UpdateTime,@Time,@Comments)";
SQLiteDBHelper db = new SQLiteDBHelper("D:\\Demo.db3");
for (char c = "A"; c <= "Z"; c++)
{
for (int i = 0; i < 100; i++)
{
SQLiteParameter[] parameters = new SQLiteParameter[]{
new SQLiteParameter("@Name",c+i.ToString()),
new SQLiteParameter("@TypeName",c.ToString()),
new SQLiteParameter("@addDate",DateTime.Now),
new SQLiteParameter("@UpdateTime",DateTime.Now.Date),
new SQLiteParameter("@Time",DateTime.Now.ToShortTimeString()),
new SQLiteParameter("@Comments","Just a Test"+i)
};
db.ExecuteNonQuery(sql, parameters);
}
}
}
public static void ShowData()
{
//查询从50条起的20条记录
string sql = "select * from test3 order by id desc limit 50 offset 20";
SQLiteDBHelper db = new SQLiteDBHelper("D:\\Demo.db3");
using (SQLiteDataReader reader = db.ExecuteReader(sql, null))
{
while (reader.Read())
{
Console.WriteLine("ID:{0},TypeName{1}", reader.GetInt64(0), reader.GetString(1));  }
}
}
希望本⽂所述对⼤家的C#程序设计有所帮助。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。