2013-05-26 82 views
6

我是一個ASP.NET初學者,所以我有一些關於如何防止SQL注入在ASP.NET中的問題。我的編程語言是VB.NET,而不是C#,我使用Microsoft Access作爲我的數據庫。SQL注入與Microsoft Access和VB.NET預防

我的問題是:

  1. 如何保護我的數據庫從SQL注入?
  2. 我一直在閱讀來自其他論壇的帖子,他們說使用 參數與存儲過程,參數與動態SQL。它們可以在Microsoft Access數據庫中實現嗎?
+0

這是否幫助?... SQL注入在MS-Access數據庫[複製] http://stackoverflow.com/questions/9392330/sql-injection-in-ms-access-database ... – Chris

+0

我相信你需要閱讀並從該主題傳遞http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx – Aristos

+0

@Chris我只是想保護我的數據庫從SQL注入,所以當用戶在文本框中輸入數據時,假設它是登錄表單,用戶輸入文本時用戶名爲textbox',則可以處理錯誤 – NPE

回答

2

以下是在VB.NET使用參數化查詢經由OleDb的一個非常簡單的ASP.NET例如:

Default.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> 

Default.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語句創建的新鍵值。