安装包
使用
const string strconn = "Data Source=data.db";
using (SQLiteConnection conn = new SQLiteConnection(strconn))
{
conn.Open();
var cmd = conn.CreateCommand();
//创建表
cmd.CommandText = "create table t1(id int,name varchar(10))";
var obj = cmd.ExecuteNonQuery();
//插入数据
cmd.CommandText = "insert into t1(id,name) values(@id,@name)";
cmd.Parameters.AddWithValue("@id", 1);
cmd.Parameters.AddWithValue("@name", "yxw");
cmd.ExecuteNonQuery();
//查询
cmd.CommandText = "select * from t1";
var rd = cmd.ExecuteReader();
while (rd.Read())
{
int id = rd.GetInt32(0);
string name = rd.GetString(1);
}
rd.Close();
//更新
cmd.CommandText = "update t1 set name=@name";
cmd.Parameters.AddWithValue("@name", "yxw1");
cmd.ExecuteNonQuery();
//删除
cmd.CommandText="delete from t1 where id=2";
cmd.ExecuteNonQuery ();
}
填充记录集
const string strconn = "Data Source=data.db";
using (SQLiteConnection conn = new SQLiteConnection(strconn))
{
dataSet1.Clear();
SQLiteDataAdapter adapter = new SQLiteDataAdapter("select * from t1",conn);
adapter.Fill(dataSet1, "t1");
}
增加行
const string strconn = "Data Source=data.db";
using (SQLiteConnection conn = new SQLiteConnection(strconn))
{
//填充记录集
dataSet1.Clear();
SQLiteDataAdapter adapter = new SQLiteDataAdapter("select * from t1", conn);
adapter.Fill(dataSet1, "t1");
//生成insert语句
SQLiteCommandBuilder scb = new SQLiteCommandBuilder(adapter);
adapter.InsertCommand = scb.GetInsertCommand();
//连接数据库
conn.Open();
//事务
var trans = conn.BeginTransaction();
try
{
//增加行
var dt = dataSet1.Tables["t1"];
var row = dt.NewRow();
row[0] = "1";
row[1] = "abc姚";
dt.Rows.Add(row);
//更新表数据
adapter.Update(dt);
//提交事务
trans.Commit();
//应用修改
dataSet1.AcceptChanges();
}
catch (Exception ex)
{
trans.Rollback();
}
}
Entity Framework 6中配置sqlite
请参考:sqlite ef6