使用System.Data.SQLite
下载地址:http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki
得到System.Data.SQLite.dll添加到工程引用;
建表,插入操作
C#代码
class="star" src="/Upload/Images/2014061010/40B102E0EF997EA6.png" alt="收藏代码" />
- 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/
建表成功。
当然这种方法插入数据效率不高,数据量大的话要使用下面这种方法:
C#代码
- 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);
- cmd.Transaction = tran;
- cmd.CommandText = "insert into student values(@id, @name, @sex)";
- cmd.Parameters.AddRange(new[] {
- new SQLiteParameter("@id", i),
- new SQLiteParameter("@name", "中国人"),
- new SQLiteParameter("@sex", "男")
- });
- cmd.ExecuteNonQuery();
- }
- tran.Commit();
- }
- }
- }
插入这样的十万条数据只需要5秒左右。
读取数据:
C#代码
- 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();
- }
数据读取成功。