当前位置:  开发笔记 > 编程语言 > 正文

Guids的SQLite参数问题

如何解决《Guids的SQLite参数问题》经验,为你挑选了1个好方法。

我在使用参数时让Guids在SQLite(0.4.8)中匹配时遇到问题,当我使用类似的东西userGuid = 'guid here'工作时,但userGuid = @GuidHere事实并非如此.有人有主意吗?

创建:

CREATE TABLE Users
(
   UserGuid TEXT PRIMARY KEY NOT NULL, 
   FirstName TEXT, 
   LastName TEXT
)

样本数据:

INSERT INTO Users (UserGuid, FirstName, LastName) 
VALUES ('e7bf9773-8231-44af-8d53-e624f0433943', 'Bobby', 'Bobston')

删除声明(工作):

DELETE FROM Users WHERE UserGuid = 'e7bf9773-8231-44af-8d53-e624f0433943'

删除声明(不工作):

DELETE FROM Users WHERE UserGuid = @UserGuid

这是一个显示我的问题的C#程序:

using System;
using System.Data.SQLite;

namespace SQLite_Sample_App
{
    class Program
    {
        static void Main(string[] args)
        {
            Do();
            Console.Read();
        }

        static void Do()
        {
            using(SQLiteConnection MyConnection = new SQLiteConnection("Data     Source=:memory:;Version=3;New=True"))
            {
                MyConnection.Open();
                SQLiteCommand MyCommand = MyConnection.CreateCommand();
                MyCommand.CommandText = @"
                    CREATE TABLE Users
                    (
                       UserGuid TEXT PRIMARY KEY NOT NULL, 
                       FirstName TEXT, 
                       LastName TEXT
                    );

                    INSERT INTO Users (UserGuid, FirstName, LastName) 
                    VALUES ('e7bf9773-8231-44af-8d53-e624f0433943', 'Bobby', 'Bobston');
                    ";
                MyCommand.ExecuteNonQuery();

                MyCommand.CommandText = "SELECT Count(*) FROM Users WHERE UserGuid = 'e7bf9773-8231-44af-8d53-e624f0433943'";
                Console.WriteLine("Method One: {0}", MyCommand.ExecuteScalar());

                MyCommand.Parameters.AddWithValue("@UserGuid", new Guid("e7bf9773-8231-44af-8d53-e624f0433943"));
                MyCommand.CommandText = "SELECT Count(*) FROM Users WHERE UserGuid = @UserGuid";
                Console.WriteLine("Method Two: {0}", MyCommand.ExecuteScalar());                    
            }
        }
    }
}

编辑:

好吧,似乎AddParamWithValue转换为Guid的16byte代表,所以我想我真的必须首先将所有guid翻译成字符串...有点烦人.



1> Robert Harve..:

尝试将GUID的字符串传递给AddWithValue调用,而不是GUID对象.

而不是

MyCommand.Parameters.AddWithValue(
    "@UserGuid", new Guid("e7bf9773-8231-44af-8d53-e624f0433943"));

做这个:

MyCommand.Parameters.AddWithValue(
    "@UserGuid", "e7bf9773-8231-44af-8d53-e624f0433943");

推荐阅读
yzh148448
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有