2014-10-17 48 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