【问题标题】:'Data type mismatch in criteria expression' with INSERT INTO non-query“条件表达式中的数据类型不匹配”与 INSERT INTO 非查询
【发布时间】:2019-02-12 10:55:28
【问题描述】:

我正在尝试将值插入数据库,但在这部分代码中遇到了上述错误:

                Dim InsertUser As OleDbCommand = New OleDbCommand("INSERT INTO [User] ([User ID], [User Name], [Total Score]) VALUES (@NO,'@Tid',@Sid);", DatabaseConnection)
            InsertUser.Parameters.AddWithValue("@NO", NumberOfUsers + 1)        
            InsertUser.Parameters.AddWithValue("@Tid", txtUserName.Text)        
            InsertUser.Parameters.AddWithValue("@Sid", CInt(lblScore.Text))     
            InsertUser.ExecuteNonQuery()

[User ID]和[T​​otal Score]为数字,[User Name]为数据库中的短文本,NumberOfUsers为整数。我不确定我做错了什么。

【问题讨论】:

  • 只需从 '@Tid' 中删除单引号
  • 你是圣人
  • 这里需要解决的不仅仅是一个修复问题。

标签: sql vb.net


【解决方案1】:

我注意到了几件事:

  • @Tid 周围的SQL 字符串中有一组额外的单引号。
  • OleDb 通常不支持命名参数(少数提供程序有例外,但通常您需要使用 ? 作为占位符)
  • 我们看不到您打开连接的位置。
  • 最好避免AddWithValue() 导致特定于数据库类型和长度的Add() 过载。这有助于提高性能并避免错误的数据库类型转换导致的问题
  • 对于大多数仅在尽可能短的时间内打开的查询使用单独的新连接对象(通常通过 Using 块控制)。使用 OleDb,这有助于限制表的争用/阻塞,并有助于减少数据库损坏。

此代码包含这些修复:

Dim sql As String = "INSERT INTO [User] ([User ID], [User Name], [Total Score]) VALUES (?, ?, ?);"
Using DatabaseConnection = New OleDbConnection("connection string here"), _
      InsertUser As New OleDbCommand(sql, DatabaseConnection)

    'Guessing at columns types. Use actual column types and lengths from the database
    InsertUser.Parameters.Add("@NO", OleDbType.Integer).Value = NumberOfUsers + 1   
    InsertUser.Parameters.Add("@Tid", OleDbType.VarWChar, 20).Value = txtUserName.Text        
    InsertUser.Parameters.Add("@Sid", OleDbType.Integer).Value = CInt(lblScore.Text)
    DatabaseConnection.Open()  
    InsertUser.ExecuteNonQuery()
End Using

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多