如何在sql中插入单引号(')? [英] How can I insert a single quote (') in sql?

查看:127
本文介绍了如何在sql中插入单引号(')?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了一些包含单引号 (') 的字符串,例如 Mayor's Office:

I got some strings that contains a single quote (') like Mayor's Office:

Dim Str = "Insert into EntryTbl(Office, DateCreated, TimeCreated)" & _
          "Values('" & OfficeBox.Text & "', " & _
          "       '" & Now.ToShortDateString & "', " & _
          "       '" & Now.ToString("HH:mm:ss") & "')"

并且 officebox.text 包含一个字符串 Mayor's Office

and the officebox.text contains a string Mayor's Office

很高兴得到任何帮助:)

Glad for any help :)

推荐答案

IMO,参数化查询更好,因为它可以防止 SQL 注入 它将为您处理转义(无需编写额外的方法来处理转义)

IMO, parametrized query is better because it prevents SQL injection and it will handle escaping for you(no need to write additional method to handle escaping)

Dim cmd As New SqlCommand("", Conn())
With cmd
     .CommandText = "Insert into tbl(Office, DateCreated, TimeCreated)" & _
                    "Values(@office,@DateCreated,@TimeCreated)"
     .Parameters.AddWithValue("@office", OfficeBox.Text)
     .Parameters.AddWithValue("@DateCreated", Now.ToShortDateString)
     .Parameters.AddWithValue("@TimeCreated", Now.ToString("HH:mm:ss"))
     .ExecuteNonQuery()
End With

<小时>

看看我该怎么做创建参数化 SQL 查询?为什么我应该?了解更多信息

这篇关于如何在sql中插入单引号(')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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