这个OleDbReader有什么问题?

时间:2015-07-06 14:31:38

标签: sql vb.net ms-access datareader oledbdatareader

在VB中工作,我连接到访问数据库,需要从表中获取值。

    user = Environment.UserName
    command.CommandText = "SELECT 'nid', 'UserName' FROM qryUSERJOBS WHERE UserName = " & user
    command.Connection = connect
    Using reader As OleDbDataReader = command.ExecuteReader()
        While reader.Read()
            record = reader("nid").ToString
        End While
    End Using

当我的代码进入Using语句时,会创建阅读器,并且会立即显示我的获胜表单,而无需读取数据库或点击包含它的例程的End Sub。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

  • 使用参数化查询
  • 避免sql注入
  • 避免像这样的引用错误
  • 使用一次性物品

Using connect As New OleDbConnection(connectionString)
    connect.Open()
    Using command As New SqlCommand(
    "SELECT nid, UserName FROM qryUSERJOBS WHERE UserName = @user", 
    connect)
        user = Environment.UserName
        command.Parameters.Add(New OleDbParameter("@user", user))

        Using reader As OleDbDataReader = command.ExecuteReader()
            While reader.Read()
                record = reader("nid").ToString
            End While
        End Using

    End Using
End Using

答案 1 :(得分:-1)

将代码放入Try ... Catch块后,我的参数出错了。我需要在user变量周围添加单引号。

代码已修复:

    user = Environment.UserName
    command.CommandText = "SELECT nid, UserName FROM qryUSERJOBS WHERE UserName = '" & user & "'"
    command.Connection = connect
    connect.Open()
    Try
        Using reader As OleDbDataReader = command.ExecuteReader()
            While reader.Read()
                record = reader("nid").ToString
            End While
        End Using
    Catch ex As Exception

    End Try

感谢大家的帮助和建议!