最近接觸了一段時間的 Sqlite3 資料庫,越來越喜歡這個輕巧的資料庫了。其優點是不需要安裝,體積小;程式中使用也不需伺服器安裝額外的驅動程式,這點在嵌入式開發中優勢顯而易見; 不過對於用慣了圖形化介面操作的我來說,剛開始還不太習慣,操作尤其不方便;在網上看了一下資料,大致說其效能是和 Access 有得一拼(基本上是處於一個數量級上);我在想:對於一個使用者幾百萬的網站來說能不能使用這一輕量級的資料庫呢?我覺得可行。在資料庫調優中我們常見的是分庫分表,這個完全可以用於 Sqlite3 上,我的思路是:比如網站共有100萬使用者, 有一個要求是使用者的每個動作都要記錄,例如每發表一篇博文,都要記錄其發布時間,發布 ip等資訊, 而這個資訊在其個人動態中展示出來,這個時候我們可以設計一個庫出來: templateDB.db3 : 其中一個表結構如下(sample):
假如某個使用者的 userid = 1051170 ; 那麼我們可以通過一定的演算法: userid/1000 = (int)1051 (意即每個 db 只服務於 1000 個使用者的某些模組)將其放在 /data/action_1051.db3 中,在做插入之前檢查一下 該庫是否存在,如不存在則拷貝一份 templatedb 到為目標庫;這樣能很大程度上減少了資料並髮帶來的鎖問題,減輕主要資料庫服務壓力。
當然這樣的設計也有不足之處:假如在投入實際生產過程一段時間後 ,我們需要改變表的某些結構或增加某個模組,這個改動將是災難性的。
最後附上使用筆記(我使用的是 ms Entlib 4.1架構 + vs 2008 ):
1. 到官方網站下載 http://www.sqlite.org/ 下載 sqlite3 並建立資料庫及表;
2. 到 http://sqlite.phxsoftware.com/ 上下載 System.Data.SQLite.dll ,然後在項目中添加引用;
3. web.config 配置
1 <connectionStrings>
2 <add name="sqlite" connectionString="data source= E:/workspace/CSharpTest/SQLiteApp/App_Data/userscore.db" providerName="System.Data.SQLite"/>
3 </connectionStrings>
4
4. 查詢:
查詢資料 1 private void bind() {
2 Database db = DatabaseFactory.CreateDatabase("sqlite");
3 string sql = "select * from userAction ";
4 DataSet ds = db.ExecuteDataSet(CommandType.Text, sql);
5 if (ds != null)
6 {
7 if (ds.Tables[0].Rows.Count > 0)
8 {
9 gdvlist.DataSource = ds;
10 gdvlist.DataBind();
11 }
12 }
13 }
14
5. 增加資料:
插入資料 1 protected void Button1_Click(object sender, EventArgs e)
2 {
3 Database db = DatabaseFactory.CreateDatabase("sqlite");
4 string sql = "insert into userAction(userid, username,nickname, scoretype, score, content, addip) "
5 + "values(@userid, @username,@nickname, @scoretype, @score, @content, @addip) ";
6 DbCommand cmd = db.GetSqlStringCommand(sql);
7 db.AddInParameter(cmd, "@userid", DbType.String, int.Parse(tbuid.Text) );
8 db.AddInParameter(cmd, "@username", DbType.String, tbuserName.Text);
9 db.AddInParameter(cmd, "@nickname", DbType.String, tbnick.Text);
10 db.AddInParameter(cmd, "@scoretype", DbType.String, tbsctype.Text );
11 db.AddInParameter(cmd, "@score", DbType.Int32, int.Parse( tbscore.Text) );
12 db.AddInParameter(cmd, "@content", DbType.String, tbcontent.Text);
13 db.AddInParameter(cmd, "@addip", DbType.String, Request.UserHostAddress);
14 db.ExecuteNonQuery(cmd);
15 Response.Write("成功!");
16 bind();
17 }
18
效果:
呵...和其他資料庫操作沒有兩樣。