SQLite参数问题与Guids

5

我在使用SQLite(0.4.8)参数时,无法使Guid匹配。当我使用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翻译为16字节的表示,所以我想我确实需要先将所有的guid翻译为字符串...有点烦人。

1个回答

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

因此,使用GUID对象而不是:

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

请执行以下操作:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接