How in VB.net we can encode string for SQL

2019-04-02 12:43发布

问题:

For example, in sql

all ` should be replaced with `` right?

Well, is there a function built in by vb.net that does that sort of thing already?

That way I do not have to encode it.

By the way, I do not access sql database directly. Basically I am creating a text file and that text file contains raw sql statements. Most of the answers deal with accessing sql data directly.

回答1:

I don't think so as I think the only case where something like this would be relevant is if you were doing inline SQL Commands without parameters.

This has a risk of SQL Injection, and therefore you should create commands like this:

Dim cmd As New SqlCommand("UPDATE [TableA] SET ColumnA=@ColumnA WHERE ID=@ID", Conn)
cmd.Parameters.Add("@ColumnA", SqlDbType.NVarChar).Value = txtColumnA.Text
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ID
cmd.ExecuteNonQuery()


回答2:

Dont try and do this! I know you are trying to avoid SQL Injection so you are to be commended for thinking about security. However rolling your own sanitisation routine is something that is easy to get wrong.

Use parameters in your query along the lines of

cmd.CommandText = "select * from customer where id=?id";

cmd.Parameters.AddWithValue("?id",CustomerIDValue);


回答3:

If you are using a string then you'll be using " in your code so you won't need to escape these characters.

Dim mySql As String = "SELECT `MyColumn` FROM `Table`"