我有一个女士访问数据库,其中包含40名学生,我想找到至少18岁的学生。
我尝试使用此代码,但是它不起作用!
Try
DataGridView1.Rows.Clear()
Dim dt As DataTable = New DBConnect().selectdata(String.Format("SELECT ID, Name FROM Students where Age > %{0}%", FlatTextBox8.Text))
For i As Integer = 0 To dt.Rows.Count - 1
DataGridView1.Rows.Add(i + 1, dt.Rows(i)(0), dt.Rows(i)(1))
Next
dt.Dispose()
dt = Nothing
Catch ex As Exception
End Try
我该怎么做?
答案 0 :(得分:0)
名称是保留字,请尝试:
String.Format("SELECT ID, [Name] FROM Students where Age > {0}", FlatTextBox8.Text))
也就是说,使用参数。
答案 1 :(得分:0)
最好使用参数化查询以避免sql注入。
此小功能将填充并返回一个DataTable
,其中包含您正在查看的值!
Private Function GetData() As System.Data.DataTable
Dim dt As New DataTable
Dim sqlCmd As String = "SELECT ID, Name FROM Students where Age > @Age"
Using myConnection As New SqlConnection(your_connection_string)
myConnection.Open()
Using myDataAdapter As New SqlDataAdapter(sqlCmd, myConnection)
myDataAdapter.SelectCommand.Parameters.Add("@Age", SqlDbType.Int) 'Change the type if your DB Table has another type
myDataAdapter.SelectCommand.Parameters("@Age").Value = Convert.ToInt16(FlatTextBox8.Text) 'Change the type if your DB Table has another type
myDataAdapter.Fill(dt)
End Using
myConnection.Close()
End Using
Return dt
End Function
现在是时候在代码中调用它了:
Try
DataGridView1.Rows.Clear()
Dim dt As DataTable = GetData()
For i As Integer = 0 To dt.Rows.Count - 1
DataGridView1.Rows.Add(i + 1, dt.Rows(i)(0), dt.Rows(i)(1))
Next
dt.Dispose()
dt = Nothing
Catch ex As Exception
MsgBox(ex.Message)
Err.Clear
End Try
您会注意到,我还添加了一个MsgBox()
,如果引发异常,它将向您显示错误消息。我发现这在调试时非常有用。