2014-10-17 50 views
0

我想将大字符串值附加到数据库中列值的现有值。此列设置为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(); 
+1

[Use Command Parameters。](http://stackoverflow.com/questions/3216233/what-is-passing-parameters-to-sql-a nd-why-do-i-need-it)这将使代码更好*和*“奇迹般地修复”问题。另外,根据实际操作,可能会跳过'initial_result'中的“阅读”。和往常一样,争取规范化的数据库.. – user2864740 2014-10-17 07:46:03

回答

2

因为使用不必要的单引号当您连接initial_resultfinalresult值。

result='" + initial_result + "'+'"+finalresult+"' 
           ^   ^

但更重要的是,您应该始终使用parameterized queries。这种字符串连接对于SQL Injection攻击是开放的。

还使用using statement来处置您的数据库连接和对象。

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(); 
    } 
} 
0

试试这个:

"update details set result=result+'" + finalresult + "' where student_id ='11'" 

这将追加和日子会把你没必要读initial_result

+0

我不认为这会产生相同的结果。它只有在'result'列有'initial_result'时才会生成相同的结果,其中'student_id ='11''。同样使用字符串连接并不是一个好方法。参数化查询始终推荐。 – 2014-10-17 08:26:56

0

如前所述,以避免SQL注入攻击,格式化代码 “Soner格尼尔”像这样:

//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 [email protected] 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(); 
} 
+0

对于'initial_result'和'finalresult',您不需要使用'ToString()'方法,因为它们已经是字符串。 – 2014-10-17 08:25:30

+0

谢谢。改性 – 2014-10-17 08:26:41