从数据库asp.net获取数据

时间:2017-05-05 01:17:06

标签: asp.net vb.net

我正在尝试使用此代码从ms访问数据库获取数据,但我不能这是我的代码是正确的

Dim query As String = "SELECT [data] FROM tabless WHERE user = '" & user.Text & "'"
Using connection As New OleDbConnection(connectionString)

    Dim cmd As New OleDbCommand(query)  
    Dim adapter As OleDbDataAdapter = New OleDbDataAdapter(query, connection)    
    Dim com As New OleDbCommand(query, connection)    
    connection.Open()
    'on the line below I get an error:  connection property has not been initialized    
    Dim reader As OleDbDataReader = cmd.ExecuteReader()

    While reader.Read()
        Label1.Text = (reader(0).ToString())
    End While

    reader.Close()

End Using

数据库

|data|
  asl

试图从数据库中获取数据并尝试在标签中显示它是可能的

1 个答案:

答案 0 :(得分:2)

您从未将cmd与关联相关联,并且您从不使用comadapter。这是你可以通过逐行逐步执行代码并检查其状态来解决的问题。

Dim query As String = "SELECT [data] FROM tabless WHERE user = '" & user.Text & "'"

Using connection As New OleDbConnection(connectionString)

    Dim cmd As New OleDbCommand(query, connection)
    connection.Open()
    Dim reader As OleDbDataReader = cmd.ExecuteReader()

    While reader.Read()
        Label1.Text = (reader(0).ToString())
    End While

    reader.Close()

End Using

此外,您的代码容易受到SQL注入攻击。您不应该将字符串连接在一起以形成查询。您应该使用参数化查询。