一、准备工作
下载System.Data.SQLite.dll,网址 System.Data.SQLite: Downloads Page
如下图所示 以32bit ,net4.6为例:有两个版本
1.第一个sqlite-netFx46-binary-Win32-2015-1.0.110.0.zip解压后要用SQLite.Interop.dll 和System.Data.SQLite.dll
2.第二个sqlite-netFx46-binary-bundle-Win32-2015-1.0.110.0.zip解压后只用System.Data.SQLite.dll
二、新建工程添加System.Data.SQLite.dll
- 新建一个C#工程
- 项目右击—>>添加—>>引用—>>浏览—>>选择System.Data.SQLite.dll—>>确定
注意:如果添加的是sqlite-netFx46-binary-x64-2015-1.0.110.0.zip解压后System.Data.SQLite.dll,还要将SQLite.Interop.dll复制到编译生成的exe目录下,该dll只能复制,不能添加引用!!!
三、部分函数说明
- 创建数据库文件
只是创建一个空白文件
static public Boolean CreateDB(string dbPath)
{
try
{
if (System.IO.File.Exists(dbPath)){
MessageBox.Show("新建数据库文件" + dbPath + "文件已存在!", "警告", MessageBoxButtons.OK);
}
else {
SQLiteConnection.CreateFile(dbPath);
}
return true;
}
catch (Exception ex)
{
throw new Exception("新建数据库文件" + dbPath + "失败:" + ex.Message);
}
}
- 除数据库文件
只是删除文件
static public Boolean DeleteDB(string dbPath)
{
try
{
if (System.IO.File.Exists(dbPath))
{
System.IO.File.Delete(dbPath);
}
return true;
}
catch (Exception ex)
{
throw new Exception("新建数据库文件" + dbPath + "失败:" + ex.Message);
}
}
- 建表
static public void CreateTable(string dbPath, string tableName, string table)
{
SQLiteConnection sqliteConn = new SQLiteConnection("data source=" + dbPath);
if (sqliteConn.State != System.Data.ConnectionState.Open)
{
sqliteConn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = sqliteConn;
//cmd.CommandText = "CREATE TABLE " + tableName + "(Name varchar,Team varchar, Number varchar)";
cmd.CommandText = "CREATE TABLE IF NOT EXISTS " + tableName+"("+ table + ")";
cmd.ExecuteNonQuery();
}
sqliteConn.Close();
}
- 删除表
static public void DeleteTable(string dbPath, string tableName)
{
SQLiteConnection sqliteConn = new SQLiteConnection("data source=" + dbPath);
if (sqliteConn.State != System.Data.ConnectionState.Open)
{
sqliteConn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = sqliteConn;
cmd.CommandText = "DROP TABLE IF EXISTS" + tableName;
cmd.ExecuteNonQuery();
}
sqliteConn.Close();
}
其余增删改查可以参考上面建表和删除表修改SQL语句实现。
cmd.CommandText = "SQL"