Jump to content

problem occurred when updating sql server table records using C#

so i want to update a record in the database on button click. i have tried the code below but it didnt work. the error i get is:Unrecognized  escape sequence. the sq part in the connection string is highlighted in red as shown in the image i have uploaded. 

 

 

        private void button7_Click(object sender, EventArgs e)
        {

            try{
            SqlConnection cn = new SqlConnection("Data Source=Dell-PC\SQLEXPRESS;Initial Catalog=employee_db;Integrated Security=True");
            cn.Open();
            SqlCommand cmd = new SqlCommand("UPDATE Posts SET description=@des WHERE id =@npid");
            cmd.Parameters.AddWithValue("@des",textBox1.Text);
            cmd.ExecuteNonQuery();
            cn.Close();
            }
            catch(Exception ex)
            {
            MessageBox.Show(ex.Message);
            }
        }

 

sq.PNG

Link to comment
Share on other sites

Link to post
Share on other sites

In C#, the backslash (\) is used to allow characters that have a special meaning to be a part of the string. Here's some example of escape sequences.

 

You either need to escape your backslash (\\)

SqlConnection cn = new SqlConnection("Data Source=Dell-PC\\SQLEXPRESS;Initial Catalog=employee_db;Integrated Security=True");

Or use a string literal (@ sign in front of string) which treats each character as it's written and doesn't require the use of escape sequences.

SqlConnection cn = new SqlConnection(@"Data Source=Dell-PC\SQLEXPRESS;Initial Catalog=employee_db;Integrated Security=True");

Side note for string literals, double quotes are added into it like so

var s = @"\this is a ""test"" string\";
var s2 = "\\this is a \"test\" string\\";
  
// Both of the above store
// \this is a "test" string\

Also, note that you're missing a parameter for @npid

SqlCommand cmd = new SqlCommand("UPDATE Posts SET description=@des WHERE id =@npid");
cmd.Parameters.AddWithValue("@des",textBox1.Text);

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×