选择大小写和错误联接多个表

时间:2019-06-13 11:37:25

标签: vb.net

Imports System.Data.OleDb
Public Class Form1
    Dim conn As OleDbConnection
    Dim cmd As OleDbCommand
    Dim da As OleDbDataAdapter
    Dim strSQL As String


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnsearch.Click
    Dim fieldselect As String = ""

    Select Case ComboBox1.Text
        Case "startYear"
            fieldselect = "startYear"
        Case "genres"
            fieldselect = "genres"
        Case "Rating"
            fieldselect = "Rating"
    End Select


    conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Movies.accdb; Persist Security Info=False;")

    strSQL = "SELECT startYear, genres, averageRating FROM (basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst)" & fieldselect & "'" & TextBox1.Text & "%'"

    conn.Open()
    da = New OleDbDataAdapter(strSQL, conn)

    Dim ds As New DataSet("Movies")

    da.Fill(ds, "Movies")

    DataGridView1.DataSource = ds.Tables("Movies")
    conn.Close()

End Sub

3 个答案:

答案 0 :(得分:0)

将数据对象保留在本地,以便可以控制在那里的关闭和处理。使用...结束使用块会为您执行此操作,即使出现错误也是如此。

“选择案例”中的所有字段是否都为同一数据类型?如果没有,您将不得不调整代码。如果您需要帮助,请告诉我数据类型,以便我修复代码。

始终使用参数来避免SQL注入。一个文本框可以包含一个“删除表”命令。参数被视为值,而不是可执行代码。

如果您稍后需要在代码中进行更新,则需要在Select中提供一个主键。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'Since your field name exactly matches the combo text the Case statement is not necessary
    Dim fieldselect As String = ComboBox1.Text
    Dim dt As New DataTable
    Using conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Movies.accdb; Persist Security Info=False;")
        Dim strSQL = "SELECT startYear, genres, averageRating FROM basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst Where " & fieldselect & " = @FieldValue;"
        Using cmd As New OleDbCommand(strSQL, conn)
            cmd.Parameters.Add("@FieldValue", OleDbType.VarChar).Value = TextBox1.Text
            conn.Open()
            dt.Load(cmd.ExecuteReader)
        End Using
    End Using
    DataGridView1.DataSource = dt
End Sub

答案 1 :(得分:0)

我想使用组合框作为程序的过滤器,我需要从2个不同的表中过滤数据。评级有自己的表,基本是不同的表。上面提到的两个字段都没有任何联系。

答案 2 :(得分:-1)

在没有上下文的情况下必须有所帮助,但是我尝试了一下:

我将替换 strSQL = "SELECT startYear, genres, averageRating FROM (basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst)" & fieldselect & "'" & TextBox1.Text & "%'"

使用

"SELECT startYear, genres, averageRating " &
"FROM basic.tconst " &
"INNER JOIN Rating.tconst on basic.tconst=Rating.tconst " & fieldselect & "'" & TextBox1.Text & "%'"

为了获得更好的帮助,您能否解释一下表Rating和Basic的工作原理以及fieldselect是什么?