时间:2021-07-01 10:21:17 帮助过:298人阅读
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的优点是便捷,安装也简单,性能也可以。
主要参考:
在c#中使用sqlite3
标签:item cal file arch sqli esc ati EDA 实现