1、首先使用NuGet引用Sqlite所需的dll文件
选用System.Data.SQLite这个包,安装
2、完成后会自己完成引用关联的另外两个dll System.Data.SQLite.Linq和System.Data.SQLite.EF6
引用文件准备就绪,下面就展开数据库的操作了
3、在需要用到的类里面别忘了引用System.Data.SQLite
4、 创建数据库
很简单对不对
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sqlite1909
{
class Program
{
static void Main(string[] args)
{
CreateDB("t123");
}
public static bool CreateDB(string db_name)
{
var fileName = "D:/"+ db_name + ".db";
SQLiteConnection.CreateFile(fileName);
return true;
}
}
}
5、接下来就可以像他数据库一样的愉快的玩耍了
代码中的几个操作,实际使用中要记得分开哦,同一个表名不能多次创建
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sqlite1909
{
class Program
{
static void Main(string[] args)
{
//CreateDB("t123");
var ds = string.Format("data source={0}", "D:/t123.db");
//创建表
using (SQLiteConnection conn = new SQLiteConnection(ds))
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "" +
"CREATE TABLE table1 (" +
"id INT(10) PRIMARY KEY," +
"name VARCHAR(20)," +
"item VARCHAR); ";
cmd.ExecuteNonQuery();
}
}
//插入数据
using (SQLiteConnection conn = new SQLiteConnection(ds))
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "INSERT INTO table1 ( id, name, item ) VALUES( '1', 'Lili','" + DateTime.Now.ToString("HH:mm:ss,fff") + "'); ";
int i = cmd.ExecuteNonQuery();
}
}
//查询数据
using (SQLiteConnection conn = new SQLiteConnection(ds))
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "select * from table1;";
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dd in dt.Rows)
{
Console.WriteLine(dd[0].ToString() + " " + dd[1].ToString() + " " + dd[2].ToString());
}
}
}
Console.ReadLine();
}
public static bool CreateDB(string db_name)
{
var fileName = "D:/"+ db_name + ".db";
SQLiteConnection.CreateFile(fileName);
return true;
}
}
}
试运行
大功告成!接下来用个操作类就可以使用了。