-3

I'm trying to get the users details in the text boxes in my form to my database in access, which should save. However i keep getting an error message every time i click to register, the following code is how i am trying to write it out:

public void AddNewUser()
{
    string filePath;
    try
    {
        filePath = (Application.StartupPath + ("\\" + DBFile));
        connection = new System.Data.OleDb.OleDbConnection((ConnectionString + filePath));
        connection.Open();
        System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
        command.Connection = connection;
        // ---set the user's particulars in the table---
        string sql = ("UPDATE enroll SET SSN=\'"
                    + (txtSSN.Text + ("\', " + ("Name=\'"
                    + (txtName.Text + ("\', " + ("Company=\'"
                    + (txtCompany.Text +("\', "
                    + (" WHERE ID=" + _UserID))))))))));
        command.CommandText = sql;
        command.ExecuteNonQuery();
        MessageBox.Show("User added successfully!", "Error");

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString(), "Error");
    }
    finally
    {
        connection.Close();
    }
}

However I think that the problem is actually coming from this section:

// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
            + (txtSSN.Text + ("\', " + ("Name=\'"
            + (txtName.Text + ("\', " + ("Company=\'"
            + (txtCompany.Text +("\', "
            + (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("User added successfully!", "Error");
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Zack
  • 7
  • 10

1 Answers1

0

Really your query is unreadable. Any kind of error could hide in that jungle of string concatenation and single quotes sprawled everywhere. (like a not necessary comma escaped probably from a fixup of a copy/paste operation)

You should use parameterized query and all of this will disappear

command.Connection = connection;
string sql = "UPDATE enroll SET SSN=?, Name=?, Company=? WHERE ID=?";
command.CommandText = sql;
command.Parameters.AddWithValue("@p1", txtSSN.Text);
command.Parameters.AddWithValue("@p2", txtName.Text );
command.Parameters.AddWithValue("@p3", txtCompany.Text);
command.Parameters.AddWithValue("@p4", _UserID);
command.ExecuteNonQuery();

Now I think that this is really more readable, no quotes to add because the framework knows the datatype of every parameter and will use the appropriate quoting required. Last but not least, no problem with Sql Injection

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286