如何在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 查询?为什么我应该?了解更多信息