Guids的SQLite参数问题

时间:2009-06-28 21:39:48

标签: c# sql database sqlite

在使用参数时,我遇到了在SQLite(0.4.8)中使用Guids匹配的问题,当我使用像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 个答案:

答案 0 :(得分:6)

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

所以而不是

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

这样做:

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