天天看點

System.Data.SQLite 中GUID的處理

項目中正好用到System.Data.SQLite,在手持上使用這個資料庫,因為要做資料同步,是以表中的主鍵都是Guid的資料類型。

在資料查詢和插入的時候,正常的使用System.Data.SQLite來插入:

public bool Add(KingToon.Model.Users model)

{

StringBuilder strSql=new StringBuilder();

strSql.Append("insert into Users(");

strSql.Append("id,num,name,passw,class_id,profession,remark,authority_id)");

strSql.Append(" values (");

strSql.Append("@id,@num,@name,@passw,@class_id,@profession,@remark,@authority_id)");

SQLiteParameter[] parameters = {

new SQLiteParameter("@id", DbType.Guid,16),

new SQLiteParameter("@num", DbType.String,512),

new SQLiteParameter("@name", DbType.String,512),

new SQLiteParameter("@passw", DbType.String,512),

new SQLiteParameter("@class_id", DbType.Guid,16),

new SQLiteParameter("@profession", DbType.String,512),

new SQLiteParameter("@remark", DbType.String,1024),

new SQLiteParameter("@authority_id", DbType.Guid,16)};

parameters[0].Value = Guid.NewGuid();

parameters[1].Value = model.num;

parameters[2].Value = model.name;

parameters[3].Value = model.passw;

parameters[4].Value = model.class_id;

parameters[5].Value = model.profession;

parameters[6].Value = model.remark;

parameters[7].Value = model.authority_id;

int

rows=DbHelperSQLite.ExecuteSql(strSql.ToString(),parameters);

if (rows > 0)

return true;

}

else

return false;

這樣插入到資料庫中的資料類型其實是一個二進制的内容,如果用sql來查詢,往往得不到正确的結果。

那麼怎麼在sql中進行guid字段的比較和查詢呢?

看下面的例子你就明白了。

select * from users where class_id =x'D19A5F9A1DB6E44D863BF07B39F843E2';

select hex(id),hex(class_id),hex(x'9A5F9AD1B61D4DE4863BF07B39F843E2') from

users; 

select

 hex('{9A5F9AD1-B61D-4DE4-863B-F07B39F843E2}');

select hex(x'9A5F9AD1B61D4DE4863BF07B39F843E2');

其中:hex()函數是将二進制内容轉換成,16進制的字元串。x'XXXXXXX'表示内容是16進制的二進制内容。

在C#中如何組合guid的字元串呢,看下面的代碼就明白:

strWhere = " station_id in (select station_id from

StationAuthority where class_id = x'"

    +

BitConverter.ToString(KingToon.BLL.SystemsIni.G_UserInfo.class_id.ToByteArray()).Replace("-",

string.Empty) + "') and " + strWhere;

      return

dal.GetList(strWhere);

需要注意的是:這裡一定要使用ToByteArray()方法,然後再轉換成16進制字元串,原因是GUID的文本表示和二進制的存儲順序并不是完全一樣,如果要知道具體的順序,debug一下ToByteArray傳回的結果就知道了。

另外一個相對而言更加簡單的辦法:

在連接配接字元串中加入參數控制,使用文本方式存儲GUID。

BinaryGUID=0