使用ADO.net和SQL中的特殊字符 [英] Working with ADO.net and special characters in SQL
本文介绍了使用ADO.net和SQL中的特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Winforms中编写一个小型应用程序,在其中我可以编写一些单词,然后使用ADO.net将它们写到SQL数据库中。
I want to write a small application in Winforms, where I will be able to write some words and write them to a SQL database using ADO.net.
I当我想使用占位符编写字符串时遇到麻烦:
I'm having trouble when I want to write a string with a placeholder like:
Give me your '%s' right now!
我的数据库中记录的是:
What is recorded in my DB is:
Give me your **"%s"** right now!
我该如何克服通过通过传输到数据库的C#更改字符串?
How can I overcome this be changing the string via C# that is transferred to my DB?
这是我代码的一部分:
public virtual int Split(global::System.Nullable<int> ID, object SplitXMLDoc, string CreatedBy)
{
global::System.Data.SqlClient.SqlCommand command = this.CommandCollection[4];
if ((ID.HasValue == true)) {
command.Parameters[1].Value = ((int)(ID.Value));
}
else {
command.Parameters[1].Value = global::System.DBNull.Value;
}
if ((SplitXMLDoc == null)) {
command.Parameters[2].Value = global::System.DBNull.Value;
}
else {
command.Parameters[2].Value = ((object)(SplitXMLDoc));
}
if ((CreatedBy == null)) {
command.Parameters[3].Value = global::System.DBNull.Value;
}
else {
command.Parameters[3].Value = ((string)(CreatedBy));
}
global::System.Data.ConnectionState previousConnectionState = command.Connection.State;
if (((command.Connection.State & global::System.Data.ConnectionState.Open)
!= global::System.Data.ConnectionState.Open)) {
command.Connection.Open();
}
int returnValue;
try {
returnValue = command.ExecuteNonQuery();
}
finally {
if ((previousConnectionState == global::System.Data.ConnectionState.Closed))
{
command.Connection.Close();
}
}
return returnValue;
}
推荐答案
您使用参数化的sql。 / p>
You use parameterized sql.
string val = "'%s'".Replace("'","\"");
string sql = "INSERT Into Table1 (value) values (@Value)";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@Value",val);
cmd.ExecuteNonQuery();
这篇关于使用ADO.net和SQL中的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文