3

I'm relatively inexperienced with professional programming, but I'm trying to write a program that interfaces with a MS Access Database. Essentially I'm gathering information in the form and trying to pass information at a new line for each entry. I have an open OleDbConnection and my test is showing that I am able to see what row will have the new entry, but when I hit the submit button, there is no error shown in the catch, but the database remains unchanged. I originally had the code in a method that I called from the click event, but I just brought the code over to the event handler to verify the issue wasn't with the call.

private void btnSubmit_Click(object sender, EventArgs e)
    {

        if (DBConnection.State.Equals(ConnectionState.Closed))
        {
            DBConnection.Open();
        }

        try
        {
            MessageBox.Show("Save Data at index: " + intRowPosition.ToString());

            OleDbCommand OledbInsert = new OleDbCommand("Insert INTO RetentionTable (DateTime,Center,CSP,MemberID,ContractNumber,RetentionType,RetentionTrigger,MemberReason,ActionTaken,Other) VALUES('" + DateTime.Now.ToString() + "','" + GetCenter("") + "','" + GetName("") + "','" + GetMemberID("") + "','" + GetContractNumber("") + "','" + GetType("") + "','" + GetTrigger("") + "','" + GetReason("") + "','" + GetAction("") + "', + GetOther("")," DBConnection);

            intRowPosition++;
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString());
            MessageBox.Show(ex.StackTrace.ToString());
        }
        finally
        {
            RefreshDBConnection();
        }

    }

Any ideas as to why this is not writing would be much appreciated.

hutchonoid
  • 32,982
  • 15
  • 99
  • 104
1337Atreyu
  • 223
  • 2
  • 5
  • 12
  • 1
    Use 'String.Format' to make your query easier to manage http://msdn.microsoft.com/en-us/library/system.string.format.aspx – Mataniko Jul 03 '13 at 14:42
  • 4
    Well, you have multiple problems but [**please use parameters**](http://csharp-station.com/Tutorial/AdoDotNet/Lesson06) instead of building SQL strings! – default.kramer Jul 03 '13 at 14:45

2 Answers2

7

There are many problems in your code above.

  • First, a command should be executed, not simply declared. (this is why the database is not being modified)
  • Second, you use reserved keywords in your statement (so even if you execute your statement, it will fail and throw an exception)
  • Third, you are concatenating strings to build the command text. A very bad move that would leave your application susceptible to SQL injection attacks
  • Fourth, the connection should be closed after usage

Let me try to write a replacement code

string cmdText = "Insert INTO RetentionTable " +
                "([DateTime],Center,CSP,MemberID,ContractNumber,RetentionType," + 
                "RetentionTrigger,MemberReason,ActionTaken,Other) " + 
                "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
 using(OleDbConnection cn = new OleDbConnection(conString))
 using(OleDbCommand cmd = new OleDbCommand(cmdText, cn))
 {
    cmd.Parameters.AddWithValue("@p1", DateTime.Now.ToString());
    cmd.Parameters.AddWithValue("@p2", GetCenter("")); 
    cmd.Parameters.AddWithValue("@p3", GetName(""));
    cmd.Parameters.AddWithValue("@p4", GetMemberID(""));
    cmd.Parameters.AddWithValue("@p5", GetContractNumber(""));
    cmd.Parameters.AddWithValue("@p6", GetType("")); 
    cmd.Parameters.AddWithValue("@p7", GetTrigger(""));
    cmd.Parameters.AddWithValue("@p8", GetReason(""));
    cmd.Parameters.AddWithValue("@p9", GetAction(""));
    cmd.Parameters.AddWithValue("@p10", GetOther(""));
    cmd.ExecuteNonQuery();
 }

The DATETIME is a reserved keyword in Access and thus, if you want to use it for your column names then you need to enclose it in square brackets.

The string concatenation is a bad practice in MSAccess but it is a fatal flaw in other database where your code could be used for Sql Injections (more difficult in Access but not impossible). If you use a parameterized query as in my example, you remove the Sql Injection problem, but also you let the framework code to pass the correct value to the database engine with the correct formatting required for dates, strings and decimals.

Another point to consider is to not have a global OleDbConnection object, but create, use and destroy the object whenever your need it. The Connection Pooling will avoid performance problems and your code will not suffer from memory leaks when a connection fails for whatever reason

I want also add that your GetXXXXX methods seems all to return strings. Remember that these methods should return values compatible with the underlying database field where you want to write

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • You could explain how your 1st item is done, which reserved keywords you're referencing in your 2nd point, and why your 3rd item is a bad move and what the good move would be. Might be a more productive answer that way. Just some suggestions. – Tombala Jul 03 '13 at 14:48
  • @Tombala, hold on a moment. It is a very long answer – Steve Jul 03 '13 at 14:50
  • Just a couple of things. First of all, (pretty minor) the values string has the second " and ) reversed. Easy fix. The issue I run into is that it's telling me that "The name 'conString' does not exist in the current context." How can I fix that then? Once again, I'm a bit amature... – 1337Atreyu Jul 03 '13 at 15:00
  • The conString variable should contain your real connection string (usually defined in the file config) – Steve Jul 03 '13 at 15:02
  • You could see examples of connection strings here at [connectionstrings.com](http://www.connectionstrings.com/) – Steve Jul 03 '13 at 15:06
  • You just knew I was agonizing over that. – 1337Atreyu Jul 03 '13 at 15:13
  • *Technically* string concatenation in a desktop application probably isn't a security vulnerability (if the user can run your application, and your application can run arbitary SQL statements, then the user almost certainly already has permissions to run arbitary SQL statements and so doesn't need SQL injection), however using parameters is still something you should get into the habbit of using every time you write code for database access. – Justin Jul 03 '13 at 15:14
  • @Justin well, we are talking about MS Access with the database file probably deployed on the same machine, so I concur with you that Sql Injection is not an overwhelming problem, but consider a desktop application that connects to a SqlServer on the internal LAN. – Steve Jul 03 '13 at 15:22
  • Same situation - if the user can run the application and the application has permission to run arbitrary SQL, then the user can also run arbitrary SQL (either the connection uses Windows Authentication or the user can just read the same connection string / credentials that the application is and use those to connect). The only situation I can see where this would be a **security** vulnerability would be some sort of heavily locked down environment where the user can only run a limited number of programs (or they accidentally use the wrong sort of quotes in your app) – Justin Jul 03 '13 at 15:32
  • 1
    Wow, thanks so much. I know that I have tons to learn, but you guys have provided so much help. I was going based off of another tutorial for linking to a mdb and that threw me into a hole that was tough to dig myself out of. I have the program working very well with much less hassle. So glad I joined StackOverflow. I'll be coming back in the future. Hopefully someday I can contribute my own answers, but for now. I'll soak up as much as I can. You honestly have no idea how relieved I am that this is up and working. Thanks a billion! – 1337Atreyu Jul 03 '13 at 20:51
1

It might be the speechmarks around the values you're putting into the database. Try changing to apostrophes.

Anyway, I strongly recommend storing the final SQL in a string and printing it to a log file or the screen and then copying that to your Access SQL editor and trying to run it. Then you'll see if there's an error and what it is.

cja
  • 9,512
  • 21
  • 75
  • 129