Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

vb.net - How to use parameters "@" in an SQL command in VB

I have this code to update my SQL database from data in a textbox, in VB. I need to use parameters in case the text contains a tic mark ,', or a quote ,", etc. Here is what I have:

dbConn = New SqlConnection("server=.SQLEXPRESS;Integrated Security=SSPI; database=FATP")
    dbConn.Open()

    MyCommand = New SqlCommand("UPDATE SeansMessage SET Message = '" & TicBoxText.Text & _
                                            "'WHERE Number = 1", dbConn)

    MyDataReader = MyCommand.ExecuteReader()
    MyDataReader.Close()
    dbConn.Close()

And this is my lame attempt to set a parameter from what I have seen on the web, which I don't understand all that well.

dbConn = New SqlConnection("server=.SQLEXPRESS;Integrated Security=SSPI; database=FATP")
    dbConn.Open()

    MyCommand = New SqlCommand("UPDATE SeansMessage SET Message = @'" & TicBoxText.Text & _
                                            "'WHERE Number = 1", dbConn)

    MyDataReader = MyCommand.ExecuteReader()
    MyDataReader.Close()
    dbConn.Close()

How do you do this? Cause if there is a ' mark in the textbox when I run the code, it crashes.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are on the right path to avoiding Bobby Tables, but your understanding of @ parameters is incomplete.

Named parameters behave like variables in a programming language: first, you use them in your SQL command, and then you supply their value in your VB.NET or C# program, like this:

MyCommand = New SqlCommand("UPDATE SeansMessage SET Message = @TicBoxText WHERE Number = 1", dbConn)
MyCommand.Parameters.AddWithValue("@TicBoxText", TicBoxText.Text)

Note how the text of your command became self-contained: it no longer depends on the value of the text from the text box, so the users cannot break your SQL by inserting their own command. @TicBoxText became a name of the variable that stands for the value in the text of the command; the call to AddWithValue supplies the value. After that, your ExecuteReader is ready to go.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...