Today, a netizen asked how to connect to the ACCESS database in C #. After searching for information and asking sammylan, the test was successful. The general process is as follows:
1. Create an Access database named csharptest. mdb, which has a table "person", which has two fields "personname". (Note: Because name is one of the key words of access, do not indicate the field name or "name" as a result; otherwise, an error may occur) and Age, which are text and numbers.
Insert two records as follows:
Personname age
Bushi 30
John 20
2. Set the ACCESS database file csharptest. the directory where MDB is located (assuming the name is access) is set to share, assuming that my machine address is 192.168.1.10, then after it is set to share, enter \ 192.168.1.10 \ access \ in the address bar to view csharptest. MDB file.
3. Open vs2008 and choose "New"> "project"> "Visual C #"> "Windows"> "Windows Forms Application" from the menu ", create a new C # form program.
4. modify the content of the code file program. cs. The complete C # code is as follows. If you have added comments, you will not explain them again.
View plaincopy to clipboardprint?
Using system. Windows. forms;
Using system. Data;
Using system. Data. oledb;
Namespace windowsformsapplication1
{
Static class Program
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[Stathread]
Static void main ()
{
// Construct the connection string
String strconnection = "provider = Microsoft. Jet. oledb.4.0 ;";
Strconnection + = @ "Data Source =\\ 192.168.1.10 \ access \ csharptest. mdb ";
Oledbconnection objconnection = new oledbconnection (strconnection); // establish a connection
Objconnection. open (); // open the connection
Oledbcommand sqlcmd = new oledbcommand (@ "select * From person where personname = 'john'", objconnection); // SQL statement
Oledbdatareader reader = sqlcmd. executereader (); // execute the query
Int age = new int ();
If (reader. Read () {// This read call is very important! If no data is written, the system will prompt that the data cannot be found during running.
Age = (INT) Reader ["Age"]; // obtain the field value
Objconnection. Close ();
Reader. Close ();
}
Application. enablevisualstyles ();
Application. setcompatibletextrenderingdefault (false );
Form1 form = new form1 ();
Form. Text = age. tostring ();
Application. Run (form );
}
}
}
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/laomai/archive/2009/04/27/4131008.aspx