【问题标题】:SQLite Parameter Issue with Guids指南的 SQLite 参数问题
【发布时间】:2010-11-06 13:13:53
【问题描述】:

在使用参数时,我遇到了在 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 转换为字符串...有点烦人。

【问题讨论】:

    标签: c# sql database sqlite


    【解决方案1】:

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

    所以不是

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

    这样做:

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

    【讨论】:

      猜你喜欢
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多