我試圖通過一個變量(月亮)獲取列表框的內容和SQL字符串的問題 下面是代碼主體中的3個SELECT字符串。最後兩個字符串工作正常 ,但第一個不是。那是我嘗試將該變量放入代碼的那個 我已經嘗試了代碼上的一些變體,但似乎沒有任何工作。是否有人有任何建議。 的SQL字符串:從列表框中獲取變量到sql字符串
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon "' ", myConnection) 'fails
da = New OleDbDataAdapter("SELECT * FROM books", myConnection) 'works
da = New OleDbDataAdapter("SELECT * FROM books WHERE author = 'molly brown' ", myConnection) 'works{
主代碼BODY
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.Odbc
Imports System.Data.DataTable
Public Class Form1
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim ds As DataSet = New DataSet
Dim da As OleDbDataAdapter
Dim tables As DataTableCollection = ds.Tables
Dim source1 As New BindingSource()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim moon As String
moon = ListBox1.Text
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Documents and Settings\james\Desktop\Authors.accdb" ' change to access database location on your computer
connString = provider & dataFile
myConnection.ConnectionString = connString
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon & "' ", myConnection) 'fails
'da = New OleDbDataAdapter("SELECT * FROM books", myConnection) 'works
'da = New OleDbDataAdapter("SELECT * FROM books WHERE author = 'molly brown' ", myConnection) 'works
da.Fill(ds, "books")
' replace "items" with the name of the table
' replace [Item Code], [Description], [Price] with the columns headers
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
End Sub
End Class
請告訴我們什麼是不工作的時候你有一個錯誤信息?只是說_不工作並沒有幫助。 – Steve
而不是在你的'OleDbAdapter'中連接你的字符串,創建一個sql變量並在那裏連接它。然後你可以看看你實際創建了什麼樣的sql,它可能會非常明顯。 – paqogomez
你也有sql注入漏洞。 – paqogomez