Java connecting to native Access databases __ Database

Source: Internet
Author: User
Tags getmessage odbc stmt access database

This code implements the method of connecting the native database.

Operation Steps:

1, access the Control Panel, open "Administrative tools → data Source (ODBC)", pop-up "ODBC Data Source Administrator", in the User DSN tab, click the selected name is "Visio Database Sample", the driver is "Microsoft Access Driver (*.MDB,*.ACCDB) option (Note: *.mdb is the database extension for Access 2003, *.ACCDB is an extension of Access 2007 and above, if you do not see this option, make sure that the Access software is installed), and then click Add button, pop-up the Create New Data Source dialog box, select Microsoft Access Driver (*.MDB,*.ACCDB) (applicable to Access 2003 and access2007), click Finish to eject the ODBC Microsoft Access Installation dialog box, enter your Access database name in the data source name, such as "book", click the "Select" button, locate the database file (such as my book database file) on your computer in the pop-up dialog box, and then click the OK button. Return to the appropriate dialog box and select OK to finish, and finally back to ODBC data Source Administrator to see the book data source appearing in the user's data source.

2, the key to connect the database statement:

To load the driver:
String sdriver= "Sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName (Sdriver);

To connect to a database:
Connection Dbcon=null;
String scon= "Jdbc:odbc:book"; Book is the name of the database
Dbcon=drivermanager.getconnection (Scon);

To perform a database operation:
Statement stmt=stmt=dbcon.createstatement ();
String ssql= "SELECT *" + "from Bookindex";
ResultSet rs=stmt.executequery (sSQL);
while (Rs.next ()) {
int num;
System.out.print (rs.getstring ("BookID") + ""); Output the value of the corresponding field
System.out.print (rs.getstring ("booktitle") + "");
System.out.print (rs.getstring ("Bookauthor"));
System.out.println ("" +rs.getfloat ("Bookprice"));
}

To close a database connection
Stmt.close ();
Dbcon.close ();

The instance code is as follows (with book database, table Bookindex, fields are: BookID, BookTitle, Bookauthor, Bookprice)


Import java.sql.*; public class Dbconntest {public static void main (String args[]) {//Step 1: Load driver String sdriver= "sun.jdbc.odbc.JdbcOdb
		Cdriver ";
		try{Class.forName (Sdriver);
			catch (Exception e) {System.out.println ("Unable to load driver");
		Return SYSTEM.OUT.PRINTLN ("Step 1: Load Driver--successful.")
		");
		Connection Dbcon=null;
		Statement Stmt=null;
		String scon= "Jdbc:odbc:book";
			try{dbcon=drivermanager.getconnection (Scon); if (dbcon!=null) {System.out.println (step 2: Connecting to the database) is successful.
			");
			//Step 3: Establish JDBC Statement Object Stmt=dbcon.createstatement (); if (stmt!=null) {System.out.println (step 3: Create a JDBC Statement object)--success.
			");
			The catch (SQLException e) {System.out.println ("Connection error:" +scon);
			System.out.println (E.getmessage ());
				if (dbcon!=null) {try{dbcon.close ();
		The catch (SQLException E2) {}} return;
			try{//executes the database query, returning the result String ssql= "SELECT *" + "from Bookindex";
			ResultSet rs=stmt.executequery (sSQL); while (Rs.next ()) {System.out.print (R)S.getstring ("BookID") + "");
				System.out.print (rs.getstring ("booktitle") + "");
				System.out.print (rs.getstring ("Bookauthor"));
			System.out.println ("" +rs.getfloat ("Bookprice"));
		The catch (SQLException e) {System.out.println (E.getmessage ()); }    finally{    try{    //Closing of Step 3 Open St
Atement Object      stmt.close ();
     System.out.println ("Close Statement object");    }     catch (SQLException e) {}     try {    //Close database connection      dbcon.close ();   &nb
sp;  System.out.println ("Close Database Connection object");        }     catch (SQLException e) {}   }  
 }
}


The above method problem: Only for this machine is valid, change a computer can not find the data source, need to reconfigure the Access data source

When connecting to a database, you can specify the path to the database directly, preferably by putting the database and source files in a directory so that you do not have to configure the data source again. The method is as follows:

Change the specified data source statement code to the following:

Previous code:

String scon= "Jdbc:odbc:book";

Post-Change Code: (Note that the database is placed in the same directory as the program source file and, if used in Eclipse, in the project folder, with the. classpath sibling.)

String Scon = "Jdbc:odbc:driver={microsoft Access driver (*.mdb)};D Bq=book.mdb";

You can also create a folder in Eclipse, such as a DB folder, and then add a table of contents to the following statement:

String Scon = "Jdbc:odbc:driver={microsoft Access driver (*.mdb)};D Bq=db/book.mdb";

Examples are as follows:

Import java.sql.*; public class Dbconntest {public static void main (String args[]) {//Step 1: Load driver String sdriver= "sun.jdbc.odbc.JdbcOdb
		Cdriver ";
		try{Class.forName (Sdriver);
			catch (Exception e) {System.out.println ("Unable to load driver");
		Return SYSTEM.OUT.PRINTLN ("Step 1: Load Driver--successful.")
		");
		Connection Dbcon=null;
		Statement Stmt=null;
		String Scon = "Jdbc:odbc:driver={microsoft Access driver (*.mdb)};D Bq=book.mdb";
			try{dbcon=drivermanager.getconnection (Scon); if (dbcon!=null) {System.out.println (step 2: Connecting to the database) is successful.
			");
			//Step 3: Establish JDBC Statement Object Stmt=dbcon.createstatement (); if (stmt!=null) {System.out.println (step 3: Create a JDBC Statement object)--success.
			");
			The catch (SQLException e) {System.out.println ("Connection error:" +scon);
			System.out.println (E.getmessage ());
				if (dbcon!=null) {try{dbcon.close ();
		The catch (SQLException E2) {}} return;
			try{//executes the database query, returning the result String ssql= "SELECT *" + "from Bookindex"; ResultSet Rs=stmt.executequery(sSQL);
				while (Rs.next ()) {System.out.print (rs.getstring ("BookID") + "");
				System.out.print (rs.getstring ("booktitle") + "");
				System.out.print (rs.getstring ("Bookauthor"));
			System.out.println ("" +rs.getfloat ("Bookprice"));
		The catch (SQLException e) {System.out.println (E.getmessage ());
				finally{try{//Close the statement object that is opened in step 3 stmt.close ();
			SYSTEM.OUT.PRINTLN ("Close Statement object");
				catch (SQLException e) {} try{//Close the statement object that is opened in step 3 dbcon.close ();
			SYSTEM.OUT.PRINTLN ("Close Database Connection object");
 The catch (SQLException e) {}}}}


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.