我想在 Winforms 中编写一个小型应用程序,我可以在其中编写一些单词并使用 ADO.net 将它们写入 SQL 数据库。
当我想编写带有占位符的字符串时遇到麻烦,例如:
Give me your '%s' right now!
我的数据库中记录的是:
Give me your **"%s"** right now!
如何通过 C# 更改传输到数据库的字符串来克服这个问题?
这是我的代码的一部分:
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。
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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)