Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert a string with a back slash into a table using C#

I'm new to C#, am still teaching myself it and am coming from Visual FoxPro programming. The problem I have is I want to insert a value from a textbox in a form that only contains computer directories. In that field I select C:\ and when I run the code I get the error: Incorrect syntax near 'C:'.

The field name that contains the directory value is lblVault and is a label object.

The code I run looks like this:

using (SqlConnection connect = new SqlConnection(@"Data Source=(LocalDB)\v11.0;" +
    "AttachDbFilename=C:\\Development\\C-Sharp\\LockItUp\\Lockitup.mdf;Integrated Security=True"))
{
    string stmt = "INSERT INTO Users(username,password,folderloc,fullname,email,cellphone) " +
    "VALUES (" + @txtUsrName.Text + "," + @txtUserPassword.Text + "," + @lblVault.Text + "," +
        @txtFullname.Text + "," + @txtEmail.Text + "," + @txtCellPhone.Text + ")";

    using (SqlCommand cmd = new SqlCommand(stmt, connect))
    {
        try
        {
            connect.Open();
            cmd.ExecuteNonQuery();
            connect.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex);
            return;
        }
    }
}

Thanks for the help!

like image 796
Bob Gatto Avatar asked Jun 08 '26 18:06

Bob Gatto


1 Answers

Easiest and safest way (google "SQL injection") is use parameters even with SQL queries. Not just it would take care of formatting strings for you, but also save you from simplest security problems.

using (SqlConnection connect = new SqlConnection(@"Data Source=(LocalDB)\v11.0;" +
            "AttachDbFilename=C:\\Development\\C-Sharp\\LockItUp\\Lockitup.mdf;Integrated Security=True"))
            {
                string stmt = "INSERT INTO Users(username,password,folderloc,fullname,email,cellphone) " +
                "VALUES (@username,@password,@folderloc,@fullname,@email,@cellphone)";

                using (SqlCommand cmd = new SqlCommand(stmt, connect))
                {
                    cmd.Parameters.Add("@username",txtUsrName.Text);
                    cmd.Parameters.Add("@password", txtUserPassword.Text);
                    cmd.Parameters.Add("@folderloc",lblVault.Text);
                    cmd.Parameters.Add("@fullname", txtFullname.Text);
                    cmd.Parameters.Add("@email",txtEmail.Text)
                    cmd.Parameters.Add("@cellphone",txtCellPhone.Text);
                    try
                    {
                        connect.Open();
                        cmd.ExecuteNonQuery();
                        connect.Close();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: " + ex);
                        return;
                    }
                }
            }
like image 179
aiodintsov Avatar answered Jun 11 '26 13:06

aiodintsov