How can I add user-supplied input to an SQL statement?

后端 未结 2 757
梦谈多话
梦谈多话 2020-11-21 07:21

I am trying to create an SQL statement using user-supplied data. I use code similar to this in C#:

var sql = \"INSERT INTO myTable (myField1, myField2) \" +
         


        
2条回答
  •  野性不改
    2020-11-21 07:49

    VB.NET Example Code

    This is the example code for the wiki answer in vb.net, assuming Option Strict On and Option Infer On.

    INSERT

    Dim sql = "INSERT INTO myTable (myField1, myField2) " & 
              "VALUES (@someValue, @someOtherValue);"
    
    Using cmd As New SqlCommand(sql, myDbConnection)
        cmd.Parameters.AddWithValue("@someValue", someVariable)
        cmd.Parameters.AddWithValue("@someOtherValue", someTextBox.Text)
        cmd.ExecuteNonQuery()
    End Using
    

    UPDATE

    Dim sql = "UPDATE myTable SET myField1 = @newValue WHERE myField2 = @someValue;"
    
    ' see above, same as INSERT
    

    SELECT

    Dim sql = "SELECT myField1, myField2 FROM myTable WHERE myField3 = @someValue;"
    
    Using cmd As New SqlCommand(sql, myDbConnection)
        cmd.Parameters.AddWithValue("@someValue", someVariable)
        Using reader = cmd.ExecuteReader()
            ' ...
        End Using
        ' Alternatively: Dim result = cmd.ExecuteScalar()
        ' if you are only interested in one value of one row.
    End Using
    

提交回复
热议问题