如何在sql中插入单引号(')?

yoy*_*yie 1 sql vb.net

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

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

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

很高兴任何帮助:)

Viv*_* S. 6

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

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
Run Code Online (Sandbox Code Playgroud)

看看如何创建参数化SQL查询?我为什么要?了解更多信息