使用 Microsoft Access 和 VB.NET 进行 SQL 注入预防 [英] SQL Injection prevention with Microsoft Access and VB.NET
问题描述
我是 ASP.NET 的初学者,所以我对如何防止 ASP.NET 中的 SQL 注入有一些疑问.我的编程语言是 VB.NET,而不是 C#,而且我使用 Microsoft Access 作为我的数据库.
I'm a beginner in ASP.NET so I have some questions about how to prevent SQL injection in ASP.NET. My programming language is VB.NET, not C#, and I'm using Microsoft Access as my database.
我的问题是:
- 如何保护我的数据库免受 SQL 注入?
- 我一直在阅读其他论坛的帖子,他们说使用参数带有存储过程,参数带有动态 SQL.它们可以在 Microsoft Access 数据库中实现吗?
推荐答案
这是一个非常简单的 ASP.NET 示例,它使用 参数化查询通过 VB.NET 中的 OleDb:
Here is a very simple ASP.NET example using a parameterized query via OleDb in VB.NET:
默认.aspx
<%@ Page Title="Home Page" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false"
CodeBehind="Default.aspx.vb" Inherits="vbOleDbSite._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<p>
First Name: <asp:TextBox ID="FirstName" runat="server"></asp:TextBox><br />
Last Name: <asp:TextBox ID="LastName" runat="server"></asp:TextBox><br />
<br />
<asp:Button ID="btnAddUser" runat="server" Text="Add User" />
<br />
Status: <span id="spanStatus" runat="server">Awaiting submission...</span>
</p>
</asp:Content>
默认.aspx.vb
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btnAddUser_Click(sender As Object, e As EventArgs) Handles btnAddUser.Click
Dim newID As Long = 0
Using con As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\__tmp estData.accdb;"
con.Open()
Using cmd As New OleDb.OleDbCommand
cmd.Connection = con
cmd.CommandText = "INSERT INTO UsersTable (LastName, FirstName) VALUES (?, ?);"
cmd.Parameters.AddWithValue("?", Me.LastName.Text)
cmd.Parameters.AddWithValue("?", Me.FirstName.Text)
cmd.ExecuteNonQuery()
End Using
Using cmd As New OleDb.OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT @@IDENTITY"
newID = cmd.ExecuteScalar()
End Using
con.Close()
End Using
Me.spanStatus.InnerText = "User """ & Me.FirstName.Text & " " & Me.LastName.Text & _
""" has been added (ID: " & newID.ToString() & ")."
End Sub
End Class
注意事项:
参数化查询使用?"而不是参数的真实"名称,因为 Access OLEDB 会忽略参数名称.参数必须按照它们在
OleDbCommand.CommandText
中出现的确切顺序定义.
The parameterized query uses "?" instead of "real" names for the parameters because Access OLEDB ignores parameter names. The parameters must be defined in the exact order that they appear in the
OleDbCommand.CommandText
.
[UsersTable] 表有一个 AutoNumber
主键,SELECT @@IDENTITY
检索由 INSERT INTO<创建的新键值/code> 语句.
The [UsersTable] table has an AutoNumber
primary key, and SELECT @@IDENTITY
retrieves the new key value created by the INSERT INTO
statement.
这篇关于使用 Microsoft Access 和 VB.NET 进行 SQL 注入预防的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!