[英]How to replace apostrophe with double apostrophe in string?
我有一個字符串
good overview of ESP's in more detail than you probably need
。
插入SQL表時會出錯。 所以我想用雙撇號替換字符串中的撇號
good overview of ESP''s in more detail than you probably need
如何在c#中操作它?
很容易:
string s = "good overview of ESP's in more detail than you probably need.";
string escaped = s.Replace("'","''");
注意:使用命令參數通常更安全。 特別是如果輸入字符串的值不受代碼控制(即用戶條目)。
使用Parameter對象。
myCommand.InsertCommand.Parameters.Add("@myString", SqlDbType.VarChar, 200);
myCommand.InsertCommand.Parameters["@myString"].Value = @"good overview of ESP's in more detail than you probably need.";
我這個問題已經很久了。 在客戶端上執行,用兩個單引號替換單引號。 如果您正在執行具有多個varchar輸入參數的sp,則此方法有效。 唯一的問題是SQL注入,即人們可以看到你在客戶端上做什么,這從來都不是一件好事。 解決這個問題的唯一方法是在服務器上使用SQL參數,就像之前所說的那樣。
myCommand.InsertCommand.Parameters.Add(“@ myString”,SqlDbType.VarChar,200); myCommand.InsertCommand.Parameters [ “@的myString”]。值
String.Replace(String,String)
應該可以正常工作。 在此示例中,您需要:
String.Replace("'", "''")
但是,我認為這不會解決您的問題。 我想你更適合尋找:
String.Replace("'", "\'")
這是MySQL的原因,我想象其他版本的SQL,希望字符串用單引號括起來。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.