C#使用System.Data.SQLite操作SQLite,
使用System.Data.SQLite 下載地址:http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki
得到System.Data.SQLite.dll添加到工程引用;
建表,插入操作
- static void Main(string[] args)
- {
- SQLiteConnection conn = null;
-
- string dbPath = "Data Source =" + Environment.CurrentDirectory + "/test.db";
- conn = new SQLiteConnection(dbPath);//創建數據庫實例,指定文件位置
- conn.Open();//打開數據庫,若文件不存在會自動創建
-
- string sql = "CREATE TABLE IF NOT EXISTS student(id integer, name varchar(20), sex varchar(2));";//建表語句
- SQLiteCommand cmdCreateTable = new SQLiteCommand(sql, conn);
- cmdCreateTable.ExecuteNonQuery();//如果表不存在,創建數據表
-
- SQLiteCommand cmdInsert = new SQLiteCommand(conn);
- cmdInsert.CommandText = "INSERT INTO student VALUES(1, '小紅', '男')";//插入幾條數據
- cmdInsert.ExecuteNonQuery();
- cmdInsert.CommandText = "INSERT INTO student VALUES(2, '小李', '女')";
- cmdInsert.ExecuteNonQuery();
- cmdInsert.CommandText = "INSERT INTO student VALUES(3, '小明', '男')";
- cmdInsert.ExecuteNonQuery();
-
- conn.Close();
- }
可以使用SQLite Database Browser來查看數據:
下載地址:http://sourceforge.net/projects/sqlitebrowser/
建表成功。
當然這種方法插入數據效率不高,數據量大的話要使用下面這種方法:
- static void Main(string[] args)
- {
- string dbPath = Environment.CurrentDirectory + "/test.db";//指定數據庫路徑
-
- using(SQLiteConnection conn = new SQLiteConnection("Data Source =" + dbPath))//創建連接
- {
- conn.Open();//打開連接
- using(SQLiteTransaction tran = conn.BeginTransaction())//實例化一個事務
- {
- for (int i = 0; i < 100000; i++ )
- {
- SQLiteCommand cmd = new SQLiteCommand(conn);//實例化SQL命令
- cmd.Transaction = tran;
- cmd.CommandText = "insert into student values(@id, @name, @sex)";//設置帶參SQL語句
- cmd.Parameters.AddRange(new[] {//添加參數
- new SQLiteParameter("@id", i),
- new SQLiteParameter("@name", "中國人"),
- new SQLiteParameter("@sex", "男")
- });
- cmd.ExecuteNonQuery();//執行查詢
- }
- tran.Commit();//提交
- }
- }
- }
插入這樣的十萬條數據只需要5秒左右。
讀取數據:
- static void Main(string[] args)
- {
- SQLiteConnection conn = null;
-
- string dbPath = "Data Source =" + Environment.CurrentDirectory + "/test.db";
- conn = new SQLiteConnection(dbPath);//創建數據庫實例,指定文件位置
- conn.Open();//打開數據庫,若文件不存在會自動創建
-
- string sql = "select * from student";
- SQLiteCommand cmdQ = new SQLiteCommand(sql, conn);
-
- SQLiteDataReader reader = cmdQ.ExecuteReader();
-
- while (reader.Read())
- {
- Console.WriteLine(reader.GetInt32(0) + " " + reader.GetString(1) + " " + reader.GetString(2));
- }
- conn.Close();
-
- Console.ReadKey();
- }
數據讀取成功。