繁体   English   中英

C#中的SQLite使用.GetBytes引发“ InvalidCastException”

[英]SQLite in C# throws “InvalidCastException” using .GetBytes

我正在尝试访问SQLite DB中的Blob列,该列最终将是指向文件或内存中的记录的指针。 我试图在SQLite中使用.GetBytes方法来获取将代表我的数据的字节数组。 使用此方法时,我不断收到InvalidCastException。 一切似乎都准备就绪,程序可以正常编译,但是在运行时,此异常不断抛出。 我四处寻找答案,似乎一切都与我拥有的代码一致,所以我在这里感到茫然,但是不幸的是,我在C#中找不到关于SQLite的任何好的文档。 代码如下

  public byte[] Output()
    {
        byte[] temp = null;
        int col = Columns + 1;
        if(read.Read())
        {
            read.GetBytes(col, 0, temp, 0, 2048); //exception is thrown here
        }
        return temp;
    }

我已经能够读取数据库中其他类型为ints和text的列,但是由于某些原因似乎无法正确显示这些blob。

编辑:新信息,这是来自异常的堆栈跟踪:

     StackTrace:
   at System.Data.SQLite.SQLiteDataReader.VerifyType(Int32 i, DbType typ)
   at System.Data.SQLite.SQLiteDataReader.GetBytes(Int32 i, Int64 fieldOffset, Byte[] buffer, Int32 bufferoffset, Int32 length)
   at SQLiteSort.Sort.Output() in C:\Users\cjones\Documents\Visual Studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Sort.cs:line 192
   at SQLiteSort.Sort.Main(String[] args) in C:\Users\cjones\Documents\Visual Studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Sort.cs:line 72
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

InnerException:

异常似乎由SQLiteDataReader.VerifyType()引发,它正在查看用于DbType.Binary类型的列,如果该列不是DbType.Binary,DbType.String或DbType.Guid,则引发异常。 我已经一遍又一遍地检查了表格,它仍然将列类型显示为斑点。

它抛出InvalidCastException的事实肯定是错误的,但是您的代码损坏temp将为null,这肯定不是。 您没有为读取数据提供任何地方。

没有注意到GetBytes的返回值,我希望您能...

编辑:只是为了检查...您正在尝试从适当的列中读取,对吗? 如果您尝试在(例如)整数列上调用GetBytes ,则InvalidCastException会比较合适。

好吧,我终于通过使用参数并将Blob设置为DbType.Binary来解决了问题。 不知道为什么这与我之前所做的有很大不同,但是现在一切正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM