6

我是 ASP.NET 的初学者,所以我对如何防止 ASP.NET 中的 SQL 注入有一些疑问。我的编程语言是 VB.NET,而不是 C#,我使用 Microsoft Access 作为我的数据库。

我的问题是:

  1. 如何保护我的数据库免受 SQL 注入?
  2. 我一直在阅读其他论坛的帖子,他们说使用带有存储过程的参数,带有动态 SQL 的参数。它们可以在 Microsoft Access 数据库中实现吗?
4

1 回答 1

2

这是一个非常简单的 ASP.NET 示例,它在 VB.NET 中通过 OleDb使用参数化查询:

默认.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 />
        &nbsp;<br />
        <asp:Button ID="btnAddUser" runat="server" Text="Add User" />
        &nbsp;<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\testData.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.

  • [UsersTable] 表有一个AutoNumber主键,并检索语句SELECT @@IDENTITY创建的新键值。INSERT INTO

于 2013-05-26T15:45:40.653 回答