C# 将值附加到数据库中的列值
我想用DB中列值的现有值附加一个大字符串值。此列设置为C# 将值附加到数据库中的列值,c#,sql,asp.net,sql-server,C#,Sql,Asp.net,Sql Server,我想用DB中列值的现有值附加一个大字符串值。此列设置为nvarchar(MAX)。但当我尝试时,只有新字符串的前几个部分附加了旧值。其他人则没有加入。请建议 string initial_result ="xxxxxx";//reading values from db column and assigning to string string final_result="yyyyyyyyyy";//lengthier one SqlCommand cmd71 = new SqlCommand(
nvarchar(MAX)
。但当我尝试时,只有新字符串的前几个部分附加了旧值。其他人则没有加入。请建议
string initial_result ="xxxxxx";//reading values from db column and assigning to string
string final_result="yyyyyyyyyy";//lengthier one
SqlCommand cmd71 = new SqlCommand("update details set result='" + initial_result + "'+'"+finalresult+"' where student_id ='11' ", con7);
cmd71.ExecuteNonQuery();
因为在连接
initial\u result
和finalresult
值时使用了不必要的单引号
result='" + initial_result + "'+'"+finalresult+"'
^ ^
但更重要的是,您应该始终使用。这种类型的字符串连接对攻击是开放的
还可用于处置数据库连接和对象
using (SqlConnection con7 = new SqlConnection(cs))
{
using (SqlCommand cmd71 = con7.CreateCommand())
{
cmd71.CommandText = "update details set result = @result where student_id ='11'";
cmd71.Parameters.Add("@result", SqlDbType.NVarChar).Value = initial_result + finalresult;
cmd71.ExecuteNonQuery();
}
}
试试这个:
"update details set result=result+'" + finalresult + "' where student_id ='11'"
这将附加,并且您无需像前面提到的“Soner Gönül”那样读取初始结果,为避免Sql注入攻击,请按如下格式格式化代码:
//reading values from db column and assigning to string
string initial_result ="xxxxxx";
//lengthier one
string final_result="yyyyyyyyyy";
string connectionstring = "your connection string here";
string query = "update details set result=@result where student_id = 11";
using(SqlConnection con = new SqlConnection(connectionstring))
{
SqlCommand cmd = new SqlCommand(query,con);
con.Open();
cmd.Parameters.Add(new SqlParameter("@result", initial_result + finalresult));
int executeresult = cmd.ExecuteNonQuery();
if(executeresult > 0)
{
Response.Write("Update Success");
}
else
{
Response.Write("Unable to Update");
}
cmd.Dispose();
}
这将使代码变得更好,并“神奇地修复”问题。此外,根据实际操作,可能会跳过
初始结果
中的“读取”。像往常一样,争取一个规范化的数据库..对于initial\u result
和finalresult
您不需要使用ToString()
方法,因为它们已经是字符串了。我认为这不会产生相同的结果。只有当result
列具有initial\u result
wherestudent\u id='11'
时,它才会生成相同的结果。此外,使用字符串连接也不是一个好方法。始终建议使用参数化查询。