How in VB.net we can encode string for SQL

烈酒焚心 提交于 2019-12-21 06:25:53

问题


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`"


来源:https://stackoverflow.com/questions/6760237/how-in-vb-net-we-can-encode-string-for-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!