2012-02-08 66 views
0

我想傳遞一個包含字符的腳本」通過傳遞「從C#到SQL Server

thisCommand.ExecuteNonQuery(); 

問題從C#到SQL服務器的字符串被表示爲「而不是」 \:字符串

thisCommand.CommandText = SQLscript; (string SQLScript) 

我怎麼能轉換所有的「字符爲\」裏面,這樣在SQL我只得到「

感謝諮詢 看完劇本:

StreamReader s = new StreamReader("export_script.sql"); 
this.SQLscript = s.ReadToEnd(); 

執行腳本:

thisCommand.CommandText = SQLscript; 
thisCommand.ExecuteNonQuery(); 

裏面的腳本我有類似:

set @cmd = 'bcp "'+ @cmd_select + '" queryout "' + @partname + '" -c -S ' + @@SERVERNAME 

你可以看到,我用「爲BCP命令

+2

請出示你如何現在這樣做(即什麼是你的'SQLscript'裏面的文字) – dasblinkenlight 2012-02-08 15:16:51

+0

[C#在字符串中有一個\無\ \]的可能重複(http://stackoverflow.com/questions/9120129/c-sharp-have-不要在字符串中傳遞數據 – 2012-02-08 15:19:21

+5

不要在sql字符串中傳遞數據總是使用'SqlCommand'和'SqlParameter'。*(破記錄...)* – 2012-02-08 15:19:32

回答

1

其實,我解決了這個問題,通過增加

thisCommand.CommandType = CommandType.Text; 

它接縫,該指令被髮送前面的「無\到SQL如果我使用這種類型的命令。

0

也許Regex.Unescape方法可以幫助你嗎?希望這可以幫助。

+0

Unescape沒有涵蓋「但thx的想法 – 2012-02-08 15:36:20

6

使用SQL參數。它會爲你做這項工作 - 不需要進行反向轉義任何危險characeters

下面是一個例子

 SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa"); 
     mySqlConnection.Open(); 
     SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); 
     mySqlCommand.CommandText = 
      "INSERT INTO Customers (" + 
      " CustomerID, CompanyName, ContactName" + 
      ") VALUES (" + 
      " @CustomerID, @CompanyName, @ContactName" + 
      ")"; 
     mySqlCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5); 
     mySqlCommand.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40); 
     mySqlCommand.Parameters.Add("@ContactName", SqlDbType.NVarChar, 30); 
     mySqlCommand.Parameters["@CustomerID"].Value = "J4COM"; 
     // The company name contains two double-quotes (") for demo purposes 
     mySqlCommand.Parameters["@CompanyName"].Value = "J4 \"Company\""; 
     mySqlCommand.Parameters["@ContactName"].IsNullable = true; 
     mySqlCommand.Parameters["@ContactName"].Value = DBNull.Value; 
     mySqlCommand.ExecuteNonQuery(); 
     Console.WriteLine("Successfully added row to Customers table"); 

     mySqlConnection.Close(); 
    } 
} 
+0

你沒有任何」字符在sql腳本中...... – 2012-02-08 15:28:23

+1

採取了在示例代碼中添加幾個反斜槓字符的自由,僅用於示例目的。 這裏最主要的是正確使用命令和參數的原理。切勿編寫自己的最終sql,但使用命名參數並讓MySql適配器完成這項工作。 – 2012-02-08 17:03:52

0

如果你想表示一個字符串字面雙引號,轉義序列是兩個雙引號。

string myString = @「< xml attribute =」「my attribute」「/>」;