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!
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With