SQLite,是一款轻型的数据库,在电脑上可以不需要安装数据库就可以使用。
在C#中使用sqlite需要引入System.Data.SQLite.dll,System.Data.SQLite.dll下载地址System.Data.SQlite.dll下载
1、 sqlite创建数据库
注意在指定数据库路径的时候要加上“Data Source”
string dbPath = "Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/winning_information.db"; conn = new SQLiteConnection(dbPath);//创建数据库实例,指定文件位置 conn.Open();//打开数据库,若文件不存在会自动创建
2、建表
string sql = "CREATE TABLE IF NOT EXISTS information(phone varchar(11), prize varchar(20));";//建表语句 SQLiteCommand cmdCreateTable = new SQLiteCommand(sql, conn); cmdCreateTable.ExecuteNonQuery();//如果表不存在,创建数据表3、添加数据
通过事物来提高添加数据的效率
using (SQLiteTransaction tran = conn.BeginTransaction())//实例化一个事务 { SQLiteCommand cmd = new SQLiteCommand(conn);//实例化SQL命令 cmd.Transaction = tran; cmd.CommandText = "insert into information values(@phone, @prize)";//设置带参SQL语句 cmd.Parameters.AddRange(new[] {//添加参数 new SQLiteParameter("@phone", textBox1.Text.Trim()), new SQLiteParameter("@prize", award) }); cmd.ExecuteNonQuery();//执行查询 tran.Commit();//提交 }4、查找数据库
SQLiteConnection conn = null; string dbPath = "Data Source =" + Environment.CurrentDirectory + "/winning_information.db"; conn = new SQLiteConnection(dbPath);//创建数据库实例,指定文件位置 conn.Open();//打开数据库,若文件不存在会自动创建 string sql = "select * from information"; SQLiteCommand cmdQ = new SQLiteCommand(sql, conn); SQLiteDataReader reader = cmdQ.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader.GetString(0) + " " + reader.GetString(1) ); } conn.Close();5、将数据库数据查询的数据赋给Datagrid(wpf)Datagridview(winform)
SQLiteConnection conn = null; string dbPath = "Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/winning_information.db"; conn = new SQLiteConnection(dbPath);//创建数据库实例,指定文件位置 conn.Open();//打开数据库,若文件不存在会自动创建 string sql = "select * from information"; // SQLiteCommand cmdQ = new SQLiteCommand(sql, conn); SQLiteDataAdapter da = new SQLiteDataAdapter(sql, conn); System.Data.DataSet ds = new System.Data.DataSet(); da.Fill(ds); dataGrid1.ItemsSource = ds.Tables[0].DefaultView; conn.Close();6、对sqlite数据库的删除操作
SQLiteConnection conn = null; string dbPath = "Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/winning_information.db"; conn = new SQLiteConnection(dbPath);//创建数据库实例,指定文件位置 conn.Open();// string sqlDele = "delect * from informstion "; SQLiteCommand cmdQ = new SQLiteCommand(sqlDele, conn); cmdQ.ExecuteNonQuery(); conn.Close();
总结来说,sqlite相对于其他数据库来说唯一简单的是在引入System .Data.Sqlite.dll后不需要其他过多的配置就可以很方便的建数据库,而对数据库的操作相对于其他数据库语句相差不大。对于庞大的数据来说,建议使用大型数据库oracle等。