System.Data.SQLite 中GUID的处理

原文: 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值