面试题答案
一键面试为防止SQL注入攻击,在Visual Basic中使用ADO.NET时可采取以下措施:
- 使用参数化查询:通过参数化查询,将用户输入作为参数传递,而非直接嵌入SQL语句,这样数据库会将参数视为数据而非代码。
以下是具体代码示例:
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim userInput As String = TextBox1.Text
Dim connectionString As String = "your_connection_string"
Using connection As New SqlConnection(connectionString)
Dim query As String = "SELECT * FROM YourTable WHERE YourColumn = @Param"
Using command As New SqlCommand(query, connection)
command.Parameters.AddWithValue("@Param", userInput)
Try
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
'处理查询结果
End While
Catch ex As Exception
MessageBox.Show("查询出错: " & ex.Message)
End Try
End Using
End Using
End Sub
End Class
- 输入验证:对用户输入进行验证,确保输入符合预期格式。例如,如果预期输入是数字,可使用
Integer.TryParse
方法验证:
Dim userInput As String = TextBox1.Text
Dim inputValue As Integer
If Integer.TryParse(userInput, inputValue) Then
'输入为有效数字,继续处理
Else
MessageBox.Show("输入必须为数字")
End If
- 白名单验证:只允许特定字符或字符集。例如,只允许字母和数字:
Imports System.Text.RegularExpressions
Dim userInput As String = TextBox1.Text
If Regex.IsMatch(userInput, "^[a-zA-Z0-9]+$") Then
'输入符合白名单,继续处理
Else
MessageBox.Show("输入只能包含字母和数字")
End If