標籤:
.Net SQLite資料庫驅動以及System.Data.SQLite.dll下載最新地址:
http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki
SQLite管理工具:
http://www.cr173.com/soft/94247.html
App.config檔案修改:
[html] view plaincopyprint?
- <?xml version="1.0"?>
- <configuration>
- <appSettings>
- <!--FailIfMissing=false表示資料庫不存在時就會自動建立-->
- <add key="DbSQLite" value="data source=|DataDirectory|DB.db3;Pooling=true;FailIfMissing=false"/>
- </appSettings>
- </configuration>
備忘:如果開發環境是4.0,而System.Data.Sqlite是比較低的版本,則可能會彈出錯誤資訊“混合模式程式集是針對“v2.0.50727”版的運行時產生的,在沒有配置其他資訊的情況下,無法在 4.0 運行時中載入該程式集”,解決方案是在上面加上:
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
</startup>
資料庫讀寫助手SqliteHelper.cs
[csharp] view plaincopyprint?
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Data;
- using System.Data.Common;
- using System.Data.SQLite;
-
-
- public class SqliteHelper
- {
- public SqliteHelper()
- {
- //
- //TODO: 在此處添加建構函式邏輯
- //
- }
-
- private static SQLiteConnection GetConnection()
- {
- string connStr = System.Configuration.ConfigurationManager.AppSettings["DbSQLite"].ToString();
- SQLiteConnection conn = new SQLiteConnection(connStr);
- conn.Open();
- return conn;
- }
-
- public static int ExecuteSql(string sql)
- {
- using (SQLiteConnection conn = GetConnection())
- {
- var cmd = new SQLiteCommand(sql, conn);
- return cmd.ExecuteNonQuery();
- }
- }
-
- public static int ExecuteScalar(string sql)
- {
- using (SQLiteConnection conn = GetConnection())
- {
- var cmd = new SQLiteCommand(sql, conn);
- object o = cmd.ExecuteScalar();
- return int.Parse(o.ToString());
- }
- }
- public static SQLiteDataReader ExecuteReader(string sql)
- {
- SQLiteConnection conn = GetConnection();
- var cmd = new SQLiteCommand(sql, conn);
- SQLiteDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
- return myReader;
- }
- public static DataSet ExecDataSet(string sql)
- {
- using (SQLiteConnection conn = GetConnection())
- {
- var cmd = new SQLiteCommand(sql, conn);
- SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
- DataSet ds = new DataSet();
- da.Fill(ds);
-
- return ds;
- }
- }
- }
表單中應用Form1.cs
[csharp] view plaincopyprint?
- //判斷表是否存在,不存在則產生
- int result = SqliteHelper.ExecuteScalar("SELECT COUNT(*) FROM sqlite_master where type=‘table‘ and name=‘tb‘");
- if (result == 0)
- {
- //建立表
- SqliteHelper.ExecuteSql("create table [tb] (id integer PRIMARY KEY autoincrement, [name] varchar(20), [createDate] datetime default (datetime(‘now‘, ‘localtime‘)))");
- }
- //插入一行資料
- result = SqliteHelper.ExecuteSql("insert into [tb](name) values (‘Luck‘)");
- if(result > 0)
- {
- string msg = "";
- //讀取資料
- SQLiteDataReader dr = SqliteHelper.ExecuteReader("select * from [tb]");
- if (dr.Read())
- {
- msg += dr[0] + "," + dr[1] + "," + dr[2];
- }
- MessageBox.Show(msg);
- }
winform中讀寫SQLite資料庫例子(轉)