Detailed steps for C # to create and connect to an Access database dynamically __ Database

Source: Internet
Author: User
Tags static class access database

detailed steps for connecting to an Access database

First, create form forms, add a button control, and add a DataGridView control.

Double-click the form and add the namespace using System.Data.OleDb;

Double-click the button, enter the button code, write the following code

OleDbConnection strconnection = new OleDbConnection ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "Employee information." MDB "+"; Persist security Info=false ");

Establish a database engine connection, and note that the data table (suffix. db) should be placed under the debug file
OleDbDataAdapter Myda = new OleDbDataAdapter ("SELECT * from Employee, strconnection");

Create an adapter to search the database with SQL statements
DataSet myds = new DataSet ();

Set up a dataset
Myda. Fill (myds, "employee");

Fill the data table with the adapter already connected to the data set myds this table with fill

Datagridview1.datasource = myDS. tables["Contact ID"];

displaying tables with display controls

Three, press F5 to run, click button, will display the corresponding SQL statement in the database table.

The following uses command and reader objects to output data under the console application.

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Using System.Data.OleDb; Namespace ConsoleApplication19 {class Program {static void Main (string[] args) {Ol
            Edbconnection Mycon =null;
            OleDbDataReader myreader=null;
                try {string strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db4.mdb;";
                Mycon = new OleDbConnection (Strcon); Mycon.
                Open ();
                String sql = "SELECT * FROM Employee";
                OleDbCommand mycom = new OleDbCommand (sql, mycon); myreader = mycom.
                ExecuteReader (); while (Myreader.read ()) {Console.WriteLine (myreader.getstring (0) + "" +myreader.getdoub

                Le (1) + "" +myreader.getstring (2) + "" +myreader.getstring (3) + "" +myreader.getstring (4));
finally {myreader.close ();                Mycon.
                
            Close ();
 }
        }
    }
}
<span style= "Font-size:24px;color: #ff0000;" ><strong> Dynamic Creation code: </STRONG></SPAN> 
Add two COM component references//microsoft ADO Ext. 2.8 for DDL and security//microsoft ActiveX Data Objects 2.8 Library   <p>&
Lt;/p><p>using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using ADOX; Using System.io;</p><p>namespace Webrequesttest.common {    public static class Accessdbhelper     {       ///<summary>   
     ///Create Access database        ///</summary>        ///<param name= "FilePath" > The full path of the database file, such as D:\\newdb.mdb</param >         public static bool Createaccessdb (string filePath)          {            ADOX.
Catalog Catalog = new Catalog ();             if (!File.exists (FilePath))             {                 Try                  {                     Catalog. Create ("Provider=microsoft.jet.oledb.4.0;ddata source=" + FilePath +);
Jet oledb:engine type=5 ");                }                  catch (System.Exception ex)                  {     
               return false;                }            }   
          return true;        }</p><p>       /// <summary>        ///Create tables in an Access database         ///</summary>        ///<param name= "FilePath" > database table file full path such as D : \\NewDb.mdb did not create </param>        ///<param name= "tablename" > table name </param>        ///<param name= "Colums" >adox. Column Object array </param>         public static void Createaccesstable (string FilePath, String tablename, params ADOX. Column[] colums         {           &nBsp ADOX.
Catalog Catalog = new Catalog ();            //Database file does not exist then create              if (! File.exists (FilePath))             {                 Try                  {                     Catalog. Create ("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + FilePath +);
Jet oledb:engine type=5 ");                }                  catch (System.Exception ex)                  {</p><p>               }            }              ADODB. Connection cn = New ADODB.
Connection ();             CN.
Open ("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + filePath, NULL, NULL,-1);             Catalog.
ActiveConnection = cn;             ADOX. Table table = new ADOX.
Table ();             table.
Name = tablename;             foreach (var column in colums)              {                 tabLe.
Columns.Append (column);            }            //column. 
parentcatalog = Catalog;            //column. properties["AutoIncrement"]. Value = true; Set up automatic growth            //table. Keys.append ("Firsttableprimarykey", keytypeenum.adkeyprimary, column, NULL, NULL); Define primary key             catalog.
Tables.append (table);             CN.
Close ();        }            / /======================================================================================== Call            //adox. column[] columns = {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;  //                      new ADOX. Column () {name= "id", type=datatypeenum.adinteger,definedsize=9},            //                      new ADOX. Column () {name= "col1", type=datatypeenum.adwchar,definedsize=50},            //                      new ADOX. Column () {name= "col2", type=datatypeenum.adlongvarchar,definedsize=50}            //               
 };           //Accessdbhelper.createaccesstable ("d:\\111.mDB "," testtable ", columns);    }} </p>
&NBSP; 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.