C# sqlite 数据库
前面介绍了怎么安装sqlite 数据库 和 sqlite 怎么创建库,怎么创建表,现在我们介绍怎么C# 怎么连接SQLite 数据库
第一步:打开VS 并引入 链接SQLite 数据库的 .dll 文件
.dll 文件可以在网上搜索下载,但是我觉得太麻烦了,我使用VS NuGet 包管理程序,免去了寻找包的问题! 打开VS 新建一个工程(我是用的Wpf,你们可以随意),右键点击引用,点击管理NuGet程序包
搜索Sqlite ,安装System.Data.SQLite 这个程序包
点击确认
安装完成
新建一个类,引用 System.Data.Sqlite 这个命名空间;
下面的代码实现了Sqlite 的增删改查
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.Data;
namespace WpfApplication1
{
public class DbHelper
{
/// <summary>
/// 返回SQLiteConnection 对象
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static SQLiteConnection GetSqlconnection ()
{
//实例化SQLite
SQLiteConnection conn = new SQLiteConnection();
try
{
//链接字符串
conn.ConnectionString = "Data Source =my.db";
//打开数据库
conn.Open();
//关闭数据库
conn.Close();
}
catch
{
throw new Exception("无法链接数据库");
}
return conn;
}
/// <summary>
/// 返回 执行(增删改)操作受影响的行数
/// </summary>
/// <returns></returns>
public static int get(string sql)
{
SQLiteConnection conn = GetSqlconnection();
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand(sql,conn);
// 返回执行的行数
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
conn.Close();
conn.Dispose();
}
}
/// <summary>
/// 返回DataTable
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public DataTable getDataTable(string sql)
{
SQLiteConnection conn = GetSqlconnection();
try
{
conn.Open();
SQLiteDataAdapter da = new SQLiteDataAdapter(sql,conn);
DataSet ds = new DataSet();
da.Fill(ds);
// 返回执行的行数
return ds.Tables[0];
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
conn.Close();
conn.Dispose();
}
}
/// <summary>
/// 返回一个DataReader 对象
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public SQLiteDataReader GetDataReader(string sql)
{
SQLiteConnection conn = GetSqlconnection();
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
//返回一个DataReader 对象
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
conn.Close();
conn.Dispose();
}
}
}
}
链接字符串 Data Source 后面可以填 数据库文件的 绝对或者相对路径,因为我把路径放在了debug 下 ,所以我填的是my.db(使用的相对路径),一般链接不上的原因就是你的数据库文件路径错了!在执行的时候调用相应的方法就可以执行增删改查了