Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

problem in send information to sql database 1

Status
Not open for further replies.

saminetemad

Programmer
Dec 13, 2010
9
IR
Hello
I wantto tell you my problem as a example:
I have two textboxes and one button in the page. When I click on the button, MoneyManagement table in sql database is updated by text of textboxes .Type of this field are nvarchar
I wrote the following code :

protected void Button1_Click(object sender, EventArgs e)
{

string strconnection;
strconnection = ConfigurationSettings.AppSettings["connectionstring"];
SqlConnection DBConnection = new SqlConnection(strconnection);
DBConnection.Open();
string sql = "";
sql = "UPDATE MoneyManagement SET ";
sql += "Name=" + "'" +TextBox1.Text + "'" + ",";
sql += "Explain=" + "'" + TextBox2.Text + "'" + " ";
sql += "WHERE ID=2 ";

SqlCommand cmd = new SqlCommand(sql, DBConnection);

cmd.ExecuteNonQuery();
DBConnection.Close();
}


When the text of textboxes are English, this code works fine. but if text of textboxes are Persian this code doesn't work fine (In the database instead of text placed a question mark)

I'm not going to define the parameters. I want to send data with sql string.



 
Since you are building the update string in code, you need to handle unicode data differently. If you did use parameters, there wouldn't be any need for the special handling because the parameter object handles that for you.

Anyway...

When you hard code a string, SQL Server interprets it as a varchar string (not an nvarchar string). To hard code an nvarchar string, you need to preface the data with N. like this:

Code:
Update MoneyManagement 
Set    Name = [!]N[/!]'Unicode data here',
       Explain = [!]N[/!]'More Unicode data'
Where  Id = 2

so... try this:

Code:
        string sql = "";
        sql = "UPDATE MoneyManagement SET ";
        sql += "Name= [!]N[/!]'" +TextBox1.Text + "'" + ",";
        sql += "Explain= [!]N[/!]'" + TextBox2.Text + "'" + "  ";
        sql += "WHERE ID=2 ";


-George
Microsoft SQL Server MVP
My Blogs
SQLCop
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Don't embed parameters into string directly - this is very bad practice and opens you to SQL injection attacks. Take a moment to educate yourself about SQL injection attacks and stop using this bad practice in your code once and for all.

PluralSight Learning Library
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top