从数据库VB中选择特定表

时间:2018-02-23 11:57:27

标签: vb.net ms-access-2010

Public Sub UserList_SelectedIn(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UserList.SelectedIndexChanged
    Dim provider As String
    Dim dataFile As String
    Dim connString As String
    Dim myConnection As OleDbConnection = New OleDbConnection
    provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
    dataFile = "\users.accdb"
    connString = provider & dataFile
    myConnection.ConnectionString = connString
    myConnection.Open()
    Chart1.Series.Add("Score") 'Adds the graph into the program
    Dim cmdd As OleDbCommand = New OleDbCommand("SELECT [Score], [Month] FROM * WHERE Table ='" & UserList.SelectedItem, myConnection)
    Dim dr2 As OleDbDataReader = cmdd.ExecuteReader
    While dr2.Read
        Chart1.Series("Score").Points.AddXY(dr2("Month").ToString, dr2("Score").ToString) 'Adds the month/score to the graph
    End While

End Sub

尝试找到一种方法来生成以下代码行,这样我就可以从特定表中选择用户可以从列表框中选择的数据。

Dim cmdd As OleDbCommand = New OleDbCommand("SELECT [Score] FROM * WHERE Table ='" & UserList.SelectedItem, myConnection)

运行时出现错误:Syntax error in FROM clause.

我因为在FROM之后的*而猜测它。

4 个答案:

答案 0 :(得分:2)

这应该是评论,但我需要50多个代表才能发表评论...但它应该向您展示如何构建您的查询

SELECT [column] FROM [table] WHERE [condition]

答案 1 :(得分:0)

我正准备添加评论,说你在命令的末尾需要另一个“'”,而且,我从来没有在这样的命令中看到过FROM *。不是说这是错的,我从来没有见过它:)。无论如何,这应该有助于解决问题,如果它们在名称中包含通配符或空格,请不要忘记括号表和字段。即使不包含空格或通配符,也可以使用括号。

Public Sub UserList_SelectedIn(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UserList.SelectedIndexChanged
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "\users.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Chart1.Series.Add("Score") 'Adds the graph into the program

Dim Table_Str As String = "[" & UserList.SelectedItem & "]"

Dim cmdd As OleDbCommand = New OleDbCommand("SELECT [Score], [Month] FROM " & Table_Str, myConnection)

Dim dr2 As OleDbDataReader = cmdd.ExecuteReader
While dr2.Read
    Chart1.Series("Score").Points.AddXY(dr2("Month").ToString, dr2("Score").ToString) 'Adds the month/score to the graph
End While

End Sub

您还可以在运行代码之前添加If语句或错误检查,以确保已从用户进行选择。

H个 鸡

答案 2 :(得分:0)

启用Option Strict将强制您使用.ToString .SelectedItem是一个对象,Option Strict需要显式转换。没有太多额外的击键,但它可以节省您的运行时错误。

 Dim cmdd As OleDbCommand = New OleDbCommand("SELECT [Score], [Month] FROM [" & ListBox1.SelectedItem.ToString & "]", myConnection)

答案 3 :(得分:-1)

懒惰对你没有好处。您应该尝试在FROM子句之后编写所有表名。也许这会解决它。