2012-02-08 63 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”“/>”;