gpt4 book ai didi

sql - 如何防止 Visual Basic 2012 中以下代码的 SQL 注入(inject)

转载 作者:行者123 更新时间:2023-12-02 21:28:07 24 4
gpt4 key购买 nike

我对如何防止 SQL 注入(inject)感到困惑,我在网上看过。我是使用存储过程,还是创建变量,我完全迷失了。

 Try
connection.Open()
’we got here so our connection to the db is sound
chosen = cboBooks.SelectedIndex
id = customerList(cboCustomers.SelectedIndex)
isbn = isbnList(cboBooks.SelectedIndex)
If number <= qty Then
Dim sql As String
sql = "INSERT INTO purchase(customer_id, ISBN, store_id, quantity)
VALUES(" & id & ", " & isbn & ", 1, " & number & ");"
Dim cmd As New SqlCommand(sql, connection)
Dim rows As Integer
rows = cmd.ExecuteNonQuery()
If rows >= 1 Then
’now update the inventory to reflect a sale
sql = "UPDATE inventory SET quantity = (quantity -" & number & ")
WHERE inventory.ISBN = " & isbn & " AND store_id = 1"
’define and execute the query command
Dim cmd2 As New SqlCommand(sql, connection)
rows = cmd2.ExecuteNonQuery

最佳答案

每当您连接 sql 并使用用户可以直接访问的变量时,您就会面临 SQL 注入(inject)的危险。

在您的情况下,修复可能看起来像这样:

 sql = "INSERT INTO purchase(customer_id, ISBN, store_id, quantity)
VALUES(@id, @isbn , 1, @number);"
Dim cmd As New SqlCommand(sql, connection)
cmd.Parameters.AddWithValue("@id", id )
cmd.Parameters.AddWithValue("@isbn", isbn )
cmd.Parameters.AddWithValue("@number", number)
Dim rows As Integer
rows = cmd.ExecuteNonQuery()

第二个查询看起来像这样:

sql = "UPDATE inventory SET quantity = (quantity - @number)
WHERE inventory.ISBN = @isbn AND store_id = 1"
Dim cmd2 As New SqlCommand(sql, connection)
cmd2.Parameters.AddWithValue("@number", id )
cmd2.Parameters.AddWithValue("@isbn", isbn )
rows = cmd2.ExecuteNonQuery

通过使用参数,字符串被转义为任何可能是恶意代码。

其他好的引用资料:

What is SQL injection?

How does the SQL injection from the "Bobby Tables" XKCD comic work?

编辑:

正如@AndyLester 在评论中指出的那样,我想建议的是使用用户数据连接到您的可执行代码中是危险的!

关于sql - 如何防止 Visual Basic 2012 中以下代码的 SQL 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23014834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com