Sqlite3 是一款优秀的数据库软件, 在嵌入式设备和移动端都有使用, 我司现在有些项目使用的数据库是 access, 说实话, 对这些不太感冒, 我还是喜欢优雅简单的东东, 于是乘着这几天休息的时间学习了下在 c# 中使用 sqlite3. 先看代码
- using System;
- using System.Data.SQLite;
- using System.IO;
- using System.Data;
- using System.Linq;
- namespace sqlite3
- {
- class Program
- {
- static string path = @"./test.sqlite";
- static SQLiteConnection connection = null;
- static void CreateDB()
- {
- connection = new SQLiteConnection("data source =" + path);
- connection.Open();
- connection.Close();
- }
- static void CreateTable()
- {
- connection.Open();
- // create table
- SQLiteCommand command = connection.CreateCommand();
- command.CommandText = "CREATE TABLE IF NOT EXISTS t1(id varchar(4), score int)";
- command.ExecuteNonQuery();
- // insert into some data
- Random random = new Random();
- for (int i = 0; i < 100; i++)
- {
- command.CommandText = string.Format("insert into t1(id, score) values({0}, {1})", i+1, random.Next());
- command.ExecuteNonQuery();
- Console.Clear();
- Console.WriteLine("wrote {0} items", i + 1);
- }
- connection.Close();
- }
- static void DeleteDB()
- {
- if (File.Exists(path))
- {
- File.Delete(path);
- }
- }
- static void QueryDB()
- {
- connection.Open();
- // query the rows
- SQLiteCommand command = connection.CreateCommand();
- command.CommandText = "select * from t1 limit 10";
- SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
- DataTable table = new DataTable();
- adapter.Fill(table);
- foreach(DataRow row in table.Rows)
- {
- Console.WriteLine($"id: {row["id"]} score: {row["score"]}");
- }
- // get the rows' count
- command.CommandText = "select count(*) from t1";
- Int64 cnt = (Int64)command.ExecuteScalar();
- Console.WriteLine($"table t1 has {cnt} rows");
- connection.Close();
- }
- static void Main(string[] args)
- {
- DeleteDB();
- CreateDB();
- CreateTable();
- QueryDB();
- Console.ReadKey();
- }
- }
- }
实现了一些简单的操作, 比较以往使用的 MySQL,sqlite3 的优点是便捷, 安装也简单, 性能也可以.
主要参考:
https://www.cnblogs.com/leemano/p/6578050.html
来源: http://www.bubuko.com/infodetail-3012160.html