sqlite 笔记 武胜

Sqlite对Guid数据的处理

首先明确两点:

1. Sqlite对Guid的存储方式是将Guid以16位byte[]的形式顺序保存在数据库中。

2.C#中的Guid对象实际上就是16位byte[],但其表达方式并不是按照byte数组顺序的(具体可以查阅MSDN,这也就是为什么Guid.ToString时显示的以“-”间隔的长度不等的原因),这是导致C#和Sqlite中Guid不匹配的本质原因。

 

解决方法:

C# to Sqlite:

string sql = string.Format("select x'{0}'", BitConverter.ToString(id1.ToByteArray()).Replace("-", ""));

Sqlite to C#:

假设数据库中的该字段名称为Id类型为guid,取出的数据为object o:

"select Id from tb;"

Guid id = (Guid)o;

假设数据库中该字段类型为blob:

select Id from tb;

Guid id = Guid.Parse((byte[])o);

表中的主键都是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返回的结果就知道了。
 
原文地址:https://www.cnblogs.com/zeroone/p/2820718.html