【C#】Creating/Querying/Modifying the .mdb databases

时间:2023-03-09 04:10:46
【C#】Creating/Querying/Modifying the .mdb databases

As for databases, there are quit many kinds such as foxpro, mysql, sqlserver, etc.

But when we need to build a project which should be portable, the .mdb(Access) databases may be one of the best choices.

Here we go.:)

1.Creating a .mdb database

Actually this simple question really got me at the beginning.But it can be easy in another way.

Firstly, we should adduct the libraries —— 'Microsoft ActiveX Data Objects 2.8 Library' and 'Microsoft ADO Ext. 2.8 for DDL and Security'.

Then,put a 'using ADOX;'.

After that you can create a database like this:

 string filename=@"c:\1.mdb";
string phrase = "provider=Microsoft.Jet.OLEDB.4.0;data source=\"" + filename + "\"";
(new Catalog()).Create(phrase);

2.Querying a .mdb database

This is much easier than that in VB6 because almost every function has been supported by the .Net Framework.

Firstly, we need to connect to the database and then query it.

After All,WE NEED TO CLOSE IT!!!!!!

Like this:

 string filename = @"c:\1.mdb";
string pwd = "";
string phrase = "provider=Microsoft.Jet.OLEDB.4.0;data source=\"" + filename + "\"";
// add password if neccessary
if (pwd != null) phrase += "; Jet OLEDB:Database Password=" + (string)pwd;
OleDbConnection conn = new OleDbConnection(phrase);
conn.Open(); //very important, don't forget it string sql = "select * from database"; //sql sentence
OleDbDataAdapter oda = new OleDbDataAdapter(sql, conn); DataTable dt1 = new DataTable(); oda.Fill(dt1); //get table of data foreach (DataRow dr in dt1.Rows)
{
foreach (DataColumn dc in dt1.Columns) //print every rows
{
console.Write((string)dr[dc]+" "); //print every columns
}
console.Writeln();
} conn.close();

3.Modifying a .mdb database

It can be quit similiar to the Quering Process.The main difference is the class we use is \( OleDbCommand \) now.

Coding like this:

 string filename = @"c:\1.mdb";
string pwd = "";
string phrase = "provider=Microsoft.Jet.OLEDB.4.0;data source=\"" + filename + "\"";
// add password if neccessary
if (pwd != null) phrase += "; Jet OLEDB:Database Password=" + (string)pwd;
OleDbConnection conn = new OleDbConnection(phrase);
conn.Open(); //very important, don't forget it string sql = "update database set abc='123' where bcd='234'"; //sql sentence
OleDbCommand comm = new OleDbCommand(sql, conn);
comm.ExecuteNonQuery(); //the feedback value is the number of rows it actually processed. conn.close();