如何在使用SQL Server 2012时在vb中使用参数化查询

时间:2016-06-15 06:17:23

标签: asp.net sql-server vb.net

我有一个错误,上面写着"必须声明标量变量"当我参数化我的查询。我是使用SQL Server的新手。我使用的版本是SQL Server 2012.以下是代码段:

   Protected Sub Main_Page
    Dim con as OleDbConnection
    Dim cmd as OleDbCommand
    Dim query as String

    con = New OleDbConnection("Provider=SQLNCLI11;Data Source=ARIES-PC\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=SchoolDB")
    con.Open()
    query = "INSERT INTO Instructors(FirstName,LastName,Address,Contact_Number) VALUES (@fname,@lname,@address,@number)"
    cmd = New OleDbCommand(query, con)
    cmd.Parameters.AddWithValue("@fname", txtFirstName.Text)
    cmd.Parameters.AddWithValue("@lname", txtLastName.Text)
    cmd.Parameters.AddWithValue("@address", txtAddress.Text)
    cmd.Parameters.AddWithValue("@number", txtContact.Text)
    cmd.ExecuteNonQuery()
    cmd.Dispose()
    con.Close()
    Response.Write(<script>alert('Success!')</script>)
End Sub

1 个答案:

答案 0 :(得分:0)

参数化查询以避免SQL注入,因此为了最佳实践,使用带参数的简单存储过程,它可以正常工作。

您的C#代码

  Protected Sub Main_Page()
        Dim con As OleDbConnection
        Dim cmd As OleDbCommand

        con = New OleDbConnection("Provider=SQLNCLI11;Data Source=ARIES-PC\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=SchoolDB")

        con.Open()
        cmd = New OleDbCommand("spSaveData", con)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@fname", txtFirstName.Text)
        cmd.Parameters.AddWithValue("@lname", txtLastName.Text)
        cmd.Parameters.AddWithValue("@address", txtAddress.Text)
        cmd.Parameters.AddWithValue("@number", txtContact.Text)
        cmd.ExecuteNonQuery()
        cmd.Dispose()
        con.Close()
        Response.Write(<script>alert('Success!')</script>)

    End Sub

您的存储过程代码

CREATE PROCEDURE spSaveData
    @fname varchar(200),
    @lname varchar(200),
    @address varchar(300),
    @number int
AS 
BEGIN
    INSERT INTO Instructors(FirstName, LastName, Address, Contact_Number) 
    VALUES (@fname, @lname, @address, @number)
END