【问题标题】:SQLite with VB.NET Value cannot be null (Help)带有 VB.NET 的 SQLite 值不能为空(帮助)
【发布时间】:2014-07-09 15:11:10
【问题描述】:

我在具有以下架构的数据库中有一个表“tblAuthors”(ID 主键自动增量,Author_Name Varchar)

表是空的。我正在尝试将记录插入表中。这是我的代码

Public Sub insertData()
    Me.mystr = "INSERT INTO tblAuthors (Author_Name) VALUES (@Author_Name)"
    modAdoDB.SetConnection()

    Me.mySQLiteCommand = New SQLiteCommand(Me.mystr, modAdoDB.con)


    Me.mySQLiteCommand.CommandText = Me.mystr
    Me.mySQLiteCommand.Parameters.AddWithValue("@Author_Name", frmAddAuthor.txtAuthorName.Text)
    Me.mySQLiteCommand = con.CreateCommand()
    Me.mySQLiteCommand.ExecuteNonQuery()
    frmAddAuthor.Close()
    MsgBox("Author record has been added.", MsgBoxStyle.Information, "Library")
    modAdoDB.CloseConnection()
End Sub

我收到错误消息 Value cannot be null 参数名称:s

ps 我可以从数据库中读取。 提前致谢

【问题讨论】:

  • 删除下面一行Me.mySQLiteCommand = con.CreateCommand()
  • @Bjørn-Roger Kringsjå 当我删除 Me.mySQLiteCommand = con.CreateCommand() 行时,我得到数据库被锁定
  • Jess,你需要打开连接。在Me.mySQLiteCommand.ExecuteNonQuery() 之前调用Me.mySQLiteCommand.Connection.Open()

标签: vb.net sqlite insert null


【解决方案1】:

你正在构建一个命令:

Me.mySQLiteCommand = New SQLiteCommand(Me.mystr, modAdoDB.con)
Me.mySQLiteCommand.CommandText = Me.mystr
Me.mySQLiteCommand.Parameters.AddWithValue("@Author_Name", frmAddAuthor.txtAuthorName.Text)

然后立即用另一个命令替换它:

Me.mySQLiteCommand = con.CreateCommand()

根据the documentationCreateCommand() 可以用来代替SQLiteCommand 构造函数,但您仍然需要设置CommandText(以及任何必要的参数)。

基本上,没有必要使用both构造函数CreateCommand()。一个或另一个会很好。所以你可以完全删除这一行:

Me.mySQLiteCommand = con.CreateCommand()

【讨论】:

  • 当我删除这一行 Me.mySQLiteCommand = con.CreateCommand() 我得到消息数据库被锁定
  • @darksyfer:你有没有打开连接?例如:Me.mySQLiteCommand.Connection.Open()。仔细查看链接文档中的示例。
  • 是.. 连接已打开 'con = New SQLiteConnection(CONNECTION_STR) con.Open()'
  • @darksyfer:你什么时候做这个? (它不在提供的代码中,但它确实应该是。)它是同一个连接对象吗?当你调试这个时,当你尝试执行命令时连接对象的运行时状态是什么?
  • @darksyfer:澄清一下,您应该在尽可能小的范围内创建/打开/使用/处置您的数据库对象。看起来此方法正在使用与其他方法具有共享范围的对象。这可能会导致问题(您现在正在发现)。与在多个上下文中重复使用相同对象的风险相比,创建新连接和命令对象的开销微不足道。
猜你喜欢
  • 2011-10-30
  • 1970-01-01
  • 1970-01-01
  • 2011-08-23
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2014-10-19
  • 2010-09-26
相关资源
最近更新 更多