问题
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'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!
How can I overcome this be changing the string via C# that is transferred to my DB?
This is part of my code:
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;
}
回答1:
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();
来源:https://stackoverflow.com/questions/20197778/working-with-ado-net-and-special-characters-in-sql