Click here to Skip to main content
15,903,362 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
OleDB and mdb...

Inserting data to the database is where I'm having problems. My scan.mdb contains 3 columns, which I need to add data row by row to. The connect/disconnect/dataGridView preload strings are concise and work well. The database just needs to overwrite everytime I create a new scan, but OleDbCommand not working well either for me.

Most examples I have found, are not clear, or just read the database.

Any help appreciated!
If I do figure it out though I will write a new article about databases, because this always stumps me. Half way into a project, then I realize I have to do database stuff, and I hit a wall.

/*
 * Begin Connection
 */

private static OleDbConnection OpenConnection()
{
    OleDbConnection conn = new OleDbConnection();
    conn.ConnectionString = @"Provider=Microsoft.JET.OlEDB.4.0;" + @"Data Source=" + Directory.GetCurrentDirectory().ToString() + @"\scanDB.mdb";
    try
    {
        conn.Open();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Failed to connect to data source");
    }
    return conn;
}

/*
 * Close Connection
 */

private static void CloseConnection(OleDbConnection conn)
{
    try
    {
        conn.Close();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
}

/*
 * Update dataGridView1
 */

private void retrieveTables()
{
    OleDbConnection conn = OpenConnection();
    OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM scan", conn);
    DataSet ds = new DataSet();
    da.Fill(ds, "scan");
    dataGridView1.DataSource = ds.Tables["scan"].DefaultView;
}
Posted
Comments
Abhinav S 17-Jul-11 12:37pm    
Well done on getting the query!
Member 8043849 17-Jul-11 12:53pm    
yup..

You need an insert query that will actually insert data into the tables.
 
Share this answer
 
Thank you for the information. Spent some more time trying to get the "insert" query to work today and puff, got it.
/*
 * Insert Data
 */
private void insertTable()
{
    OleDbConnection conn = GetConnection();
    OleDbCommand cmd;
    OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM scan", conn);
    cmd = new OleDbCommand("INSERT INTO scan ([COL1], [COL2], [COL3]) " +
               "VALUES (@Var1, @Var2, @Var3)", conn);

    cmd.Parameters.Add("@Var1", OleDbType.VarChar).Value = "1";
    cmd.Parameters.Add("@Var2", OleDbType.VarChar).Value = "2";
    cmd.Parameters.Add("@Var3", OleDbType.VarChar).Value = "3";
    cmd.ExecuteNonQuery();
    da.InsertCommand = cmd;
    conn.Close();

    // Update datagridview1
    retrieveTables();
}


Thanks again works great!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900