Now, we are talking something about Office Access(2007) operation using C#. And I will show you how to create a access db file, including creating new table, insert and update data item. Before we start coding, we should add references "Microsoft ADO Ext. 2.8 for DDL and Security" and "Microsoft ActiveX Data Objects 2.8 Library", and of course the related namespace.
1. Create new Access database using ADOX:
Create Database Using ADOX
/**//// <summary>
/// Create access db file, add a new table with columns.
/// </summary>
/// <param name="accessFile">Access db file to be created</param>
public void CreateDatabaseUsingADOX(string accessFile)
{
try
{
ADOX.CatalogClass cat = new ADOX.CatalogClass();
if (!File.Exists(accessFile))
{
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + accessFile + ";");
//cat = null;
}
cat = null;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.Source);
}
}
2. Next we will create a new table with several columns for this database, first we try to use ADOX:
Create Table Using ADOX
/**//// <summary>
/// Create new table and add columns.
/// </summary>
/// <param name="accessFile">Access db file</param>
public void CreateTableUsingADOX(string accessFile)
{
try
{
ADOX.CatalogClass cat = new ADOX.CatalogClass();
ADODB.Connection conn = new ADODB.Connection();
conn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + accessFile, null, null, -1);
cat.ActiveConnection = conn;
//Create a new table
ADOX.TableClass tbl = new ADOX.TableClass();
tbl.ParentCatalog = cat;
tbl.Name = "MyTable";
//Add an automatic increasing column
ADOX.ColumnClass col = new ADOX.ColumnClass();
col.ParentCatalog = cat;
//First set data type
col.Type = ADOX.DataTypeEnum.adInteger;
//Column name
col.Name = "ID";
col.Properties["Jet OLEDB:Allow Zero Length"].Value = false;
col.Properties["AutoIncrement"].Value = true;
tbl.Columns.Append(col, ADOX.DataTypeEnum.adInteger, 0);
//Add a text column
ADOX.ColumnClass col2 = new ADOX.ColumnClass();
col2.ParentCatalog = cat;
col2.Name = "Description";
col2.Properties["Jet OLEDB:Allow Zero Length"].Value = false;
tbl.Columns.Append(col2, ADOX.DataTypeEnum.adVarChar, 25);
//Set primary key
tbl.Keys.Append("PrimaryKey", ADOX.KeyTypeEnum.adKeyPrimary, "id", "", "");
//Append the table to db file
cat.Tables.Append(tbl);
conn.Close();
tbl = null;
cat.ActiveConnection = null;
cat = null;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.Source);
}
}
3. And we can also use OleDb command to create new table, let's have a look:
Create Table Using OleDb Command
/**//// <summary>
/// Create new table with columns.
/// </summary>
/// <param name="accessFile">Access db file</param>
public void CreateTableUsingOleDbCommand(string accessFile)
{
try
{
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + accessFile + ";";
OleDbConnection accessConn = new OleDbConnection(connstr);
accessConn.Open();
//Create a new table
OleDbCommand myCommand = new OleDbCommand("create table MyTable (ID integer not null,Description char(50),primary key(ID))", accessConn);
myCommand.ExecuteNonQuery();
accessConn.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.Source);
}
}
4. Following are 'insert', 'query', 'update' and 'delete' operations:
Query And Update Using OleDb Command
/**//// <summary>
/// Query and update data from table using OleDb command
/// </summary>
/// <param name="accessFile">Access db file</param>
public void QueryAndUpdateUsingOleDbCommand(string accessFile)
{
try
{
//Suppose the table name is 'MyTable'
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + accessFile + ";";
OleDbConnection accessConn = new OleDbConnection(connstr);
accessConn.Open();
//Insert data to DB table.
//No need to insert data for automatic increasing column.
string strCmd = String.Format("insert into MyTable(ID, Description) values('{0}','{1}')", 1, "This is the first row");
OleDbCommand cmd = new OleDbCommand(strCmd, accessConn);
cmd.ExecuteNonQuery();
strCmd = String.Format("insert into MyTable(ID, Description) values('{0}','{1}')", 2, "This is the second row");
cmd = new OleDbCommand(strCmd, accessConn);
cmd.ExecuteNonQuery();
//Query
strCmd = String.Format("select * from MyTable");
cmd = new OleDbCommand(strCmd, accessConn);
OleDbDataReader odrReader = cmd.ExecuteReader();
while(odrReader.Read())
{
//Get data according to column name.
Console.WriteLine(odrReader["ID"].ToString() + " " + odrReader["Description"].ToString());
}
//Update
strCmd = String.Format("update MyTable set Description = '{0}' where ID = {1}", "This is row 1", 1);
cmd = new OleDbCommand(strCmd, accessConn);
cmd.ExecuteNonQuery();
//Delete
strCmd = String.Format("delete from MyTable where ID = 2");
cmd = new OleDbCommand(strCmd, accessConn);
cmd.ExecuteNonQuery();
accessConn.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.Source);
}
}
I have already had a test for all the functions, if you get any problem please let me know.
Go to my home page for more posts