【发布时间】:2009-11-10 20:25:12
【问题描述】:
edit2:解决方案SQLite and `Object reference not set` exception
我很难理解我的错误。
edit1:我设置了我的定义以使我的代码成为单线程的。问题消失了。所以这似乎是一个竞争条件。
我收到以下错误。但并非总是如此,我注意到如果我不设置休息时间或者我快速通过它们,我也不会例外。当在var o = command.ExecuteScalar(); 或其前面的行设置断点并等待 10 多秒(我使用系统时钟进行检查,不计数)时,它总是会出现异常(我尝试了两次,但是根据我注意到异常发生的情况只有当我休息几秒钟以上时)。
我不明白为什么我会收到错误消息。我打印了 sql 语句和我提供给它的参数值,我可以看到它的正确值。这是怎么回事!?!困扰我的是 COUNT(*) 有效,但插入无效。
这是我的代码
else
{
command.CommandText = "SELECT COUNT(*) FROM link_list;";
var o = command.ExecuteScalar();
int status = (int)r.status;
command.CommandText = "UPDATE link_list SET status=@status WHERE id=@id;";
command.Parameters.Add("@status", System.Data.DbType.Byte).Value = status;
command.Parameters.Add("@id", System.Data.DbType.Int32).Value = info.linkId;
Console.WriteLine("CommandText {0} {1} {2}", command.CommandText, status, info.linkId);
command.ExecuteNonQuery();
Console.WriteLine("CommandText no exception");
}
其他地方
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
我的输出
CommandText UPDATE link_list SET status=@status WHERE id=@id; 5 108
The thread '<No Name>' (0xbc8) has exited with code 0 (0x0).
A first chance exception of type 'System.NullReferenceException' occurred in System.Data.SQLite.dll
Object reference not set to an instance of an object.
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
at WebDLManager.DB.updateStatus(DLInfo info, ReturnVal r) in C:\dev\source\prvTrunk\WebDLManager\WebDLManager\db.cs:line 134
at WebDLManager.SiteBase.threadStart() in C:\dev\source\prvTrunk\WebDLManager\WebDLManager\SiteType.cs:line 241
The program '[1360] WebDLManager.vshost.exe: Managed' has exited with code 0 (0x0).
根据要求
//this is called through form_load
connection = new SQLiteConnection("Data Source=mydb.sqlite3;Version=3");
command = new SQLiteCommand(connection);
connection.Open();
【问题讨论】:
-
您能在定义
command的位置添加行吗? -
SqlLiteCommand.Parameters 有 AddWithValue 方法吗?将 int 转换为字节有问题吗?
-
Traveling Tech Guy:结果我不小心在线程之间共享命令,即使调试数据看起来正确。
-
接受它,而不是添加指向解决您问题的答案的链接。尽管这是一个老问题,但 Adam 会很感激,其他正在寻找解决方案的人也会很感激。