在VB.net中删除一个字符串(加斜杠)? [英] Escape a string (add slashes) in VB.net?

查看:241
本文介绍了在VB.net中删除一个字符串(加斜杠)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常简单的问题(令人惊讶的是我在任何地方找不到类似的问题):如何在VB.net中转义表单数据?我有这样的各种行:

Very simple question (surprisingly I can't find a similar question anywhere): how do I escape form data in VB.net? I have various lines like this:

Dim query As String = "exec sp_Message_insert @clientid='" + pClientId + "', @message='" + pMessage + "', @takenby='" + pUserId + "', @recipients='" + pRecipients + "'"

如果我在消息中使用撇号,那么当然这会使查询变得螺旋起来。我已经查看了字符串上的智能感知功能,但没有看到任何适当的...

If I use an apostrophe in the message then of course this screws up the query. I've looked through the intellisense functions on the string but don't see anything appropriate...

推荐答案

意思是逃跑? VB.NET没有像c风格语言一样的转义。

What exactly do you mean by escaping? VB.NET doesn't have 'escaping' in the same way that c-style languages do.

现在,如果要确保pClientId变量中没有单个qoutes,那么您有两个选项:

Now, if you want to ensure that there are no single-qoutes in the pClientId variable, then you have two options:

选项1(不推荐用于这种情况):做一个简单的替换。即

Option 1 (not recommended for this scenario): do a simple replace. I.e.

pClientId = String.Replace(pClientId, "'","''")

但是,如上所述,我不会这样做,似乎是一个SQL命令。我会做的是
选项2:使用数据参数在sql命令中将参数传递给您的数据库

But, as noted, I would NOT do this for what appears to be a SQL Command. What I would do is Option 2: use data parameters to pass parameters to your DB during sql commands

例如:

Dim cn As New SqlConnection(connectionString)
Dim cmd As New SqlCommand
cn.Open
cmd.Connection=cn
cmd.CommandType=CommandType.StoredProcedure
cmd.CommandText= "sp_Message_insert"
cmd.Parameters.add(New SqlParameter("@clientid", pClientId)
cmd.Parameters.add(New SqlParameter("@message", pMessage)
cmd.Parameters.add(New SqlParameter("@takenby", pUserId)
cmd.Parameters.add(New SqlParameter("@recipients", pRecipients)
cmd.ExecuteNonQuery

这篇关于在VB.net中删除一个字符串(加斜杠)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆