大家好我是visual basic.net的新手,我试图将查询结果显示到数据网格视图中,我有下面的代码,但它给了我一个错误和highlitingFillTable下面的代码,请指导我如何打印查询到数据网格。感谢
Imports System.Data.OleDb
Public Class SearchForm
Dim con As New OleDbConnection
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Statd.SelectedIndexChanged
End Sub
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
con.Open()
Dim sqlQuery As String
Dim sqlCommand As New OleDbCommand
Dim sqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim empNum As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
empNum = eNumText.Text
empLname = empLnameText.Text
empDept = Deptd.Text
empStat = Statd.Text
'sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '+ empLnameText.Text +' "
sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '+ empLnameText.Text +"
' MsgBox("Employee Number " + empNum + empLname + empDept + empStat) 'test statement
With sqlCommand
.CommandText = sqlQuery
.Connection = con
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(Table)
End With
For i = 0 To Table.Rows.Count - 1
With DataGridView1
.Rows.Add(Table.Rows(i)("EmpID"), Table.Rows(i)("FirstName"), Table.Rows(i)("LastName"), Table.Rows(i)("Department"), Table.Rows(i)("Position"), Table.Rows(i)("Status"), Table.Rows(i)("Years"))
End With
Next
End With
con.Close()
End Sub
答案 0 :(得分:2)
您的字符串连接中有几个错误,形成了select语句
sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '" + empLnameText.Text + "'"
但这不是查询获取用户输入的数据库的正确方法。您需要使用参数化查询
sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like ?"
With sqlCommand
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("@name", empLnameText.Text)
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
然后你只需将DataGridView1.DataSource设置为你的表,你就没有任何循环来填充网格
使用字符串连接是一种不好的做法,因为您的代码是Sql Injection attack的一个简单目标(非常严重的漏洞),但是,如果您的enpLName.Text包含单引号,则使用的字符串连接将是yeld一个无效的sql语句。