README.md
December 5, 2022 · View on GitHub
Description
This will teach you how to connect to a Microsoft Access database. It's also a great overview of JDBC. Once you are connected, you may run any SQL statement that is allowable on Access, such as SELECT, etc. You don't even have to have MS Access installed to run this tutorial - it shows you how to make a blank one without Access!
More Info
| Submitted On | |
| By | Jeff Patterson |
| Level | Beginner |
| User Rating | 4.8 (2833 globes from 591 users) |
| Compatibility | Java (JDK 1.1), Java (JDK 1.2) |
| Category | Databases/ JDBC |
| World | Java |
| Archive File |
Source Code
Sorry if the formatting is a little screwed up on this - PlanetSourceCode seems to modify my HTML just a little when I upload it...it should still all be readable enough...
If you find this useful, please vote for me!
and it's also
A Super Quick Overview of JDBC Basics
This will teach you how to connect to a Microsoft Access database. Once you are connected, you may run any SQL statement that is allowable on Access, such as:
- a
SELECTstatement to retrieve data - an
INSERTstatement to add data - a
DELETEstatement to remove data - an
CREATE TABLEstatement to build a new table - a
DROP TABLEstatement to destroy a table
Steps to take:
There are three things we need to do to manipulate a MS Access database:
1) Set up Java to undestand ODBC,
2) Get a connection to our MS Access Database,
3) Run a SQL statement.
1) First we need to set up Java to understand how to communicate with an ODBC data source
There are two ways to get a connection from your Microsoft Access Database:
- Get a connection by accessing the Database Directly
The simpler way, but may not work on all systems! - Set the Access Database up as an ODBC DSN and get a connection through that
A little more complex, but will work on any system, and will work even if you don't already have a Microsoft Access Database!
3) Once you have gained access to the Database (been granted a connection), you are ready to try:
- Running a SQL Statement on your Access Database
This is the section that you will be most interested in - if you're impatient, you might want to start here...but please come back and read it all!
In addition, please refer to the section at the end of this document:
- What I assume you already know
Plus a little additional reading.
| Step 1) Set up your DriverManager to understand ODBC data sources | BACK TO TOP |
java.sql.Connection, is handed out by the DriverManager. We tell the DriverManager what type of driver to use to handle the connections to databases, and from there, ask it to give us a connection to a particular database of that type.For this tutorial, we are interested in accessing a Microsoft Access database. Microsoft has developed a data access method called ODBC, and MS Access databases understand this method. We cannot make a connection directly to an ODBC data source from Java, but Sun has provided a bridge from JDBC to ODBC. This bridge gives the DriverManager the understanding of how to communicate with an ODBC (ie a MS Access) data source.
So the first thing we'll do is set up our DriverManager and let it know that we want to communicate with ODBC data sources via the JDBC:ODBC bridge. We do this by calling the static forName() method of the Class class. Here is an entire program that accomplishes what we're after:
//save this code into a file called Test.java and compile it |
We're now ready to try and get a connection to our specific database so we can start to run SQL statements on it!
| Step 2 method 1) Get a connection by direct access | BACK TO TOP |
Here is a complete sample program getting a connection to a MS Access database on my hard drive at D:\java\mdbTEST.mdb. This sample includes the lines required to set the DriverManager up for ODBC data sources:
//save this code into a file called Test.java and compile it |
Notice that this time I imported the java.sql package - this gives us usage of the java.sql.Connection object.
The line that we are interested in here is the line
Connection con = DriverManager.getConnection( database ,"","");
What we are trying to do is get a Connection object (named con) to be built for us by the DriverManager. The variable database is the URL to the ODBC data source, and the two sets of empty quotes ("","") indicate that we are not using a username or password.
In order to have this program run successfully, you have to have an MS Access database located at filename location. Edit this line of code and set it to a valid MS Access database on your machine. If you do not already have an MS Access database, please jump down to Set the Access Database up as an ODBC DSN section, which shows how to create an empty MS Access database.
If you do have a MS Access database, and this is working correctly, then you're ready to Run an SQL Statement!
| Step 2 method 2) Set up a DSN and get a connection through that | BACK TO TOP |
As we learned earlier, MS Access data bases can be connected to via ODBC. Instead of accessing the database directly, we can access it via a Data Source Name (DSN). Here's how to set up a DSN on your system:
- Open Windows' ODBC Data Source Administrator as follows:
- In Windows 95, 98, or NT, choose Start > Settings > Control Panel, then double-click the ODBC Data Sources icon. Depending on your system, the icon could also be called ODBC or 32bit ODBC.
- In Windows 2000, choose Start > Settings > Control Panel > Administrative Tools > Data Sources.
- In the ODBC Data Source Administrator dialog box, click the System DSN tab.
- Click Add to add a new DSN to the list.
- Scroll down and select the Microsoft Access (.MDB) driver
- Type in the name "mdbTEST" (no quotes, but leave the cases the same) for the Data Source Name
- Click CREATE and select a file to save the database to (I chose "d:\java\mdbTEST.mdb") - this creates a new blank MS Access database!
- Click "ok" all the way out
//save this code into a file called Test.java and compile it |
As stated in the code, modify the variable dataSourceName to whatever you named your DSN in step 5 from above.
If this complies and runs successfully, it should produce no output. If you get an error, something isn't set up right - give it another shot!
Once this is working correctly, then you're ready to Run an SQL Statement!
| Step 3) Running a SQL Statement on your Access Database | BACK TO TOP |
- Create a Statement from the connection you have made
- Get a ResultSet by executing a query (your insert/delete/etc. statement) on that statement
Refer to the following complete program for an understanding of these concepts (details follow):
This code assumes that you have used the DSN method (Step 2 method 2) to create a DSN named mdbTest. If you have not, you'll need to modify this code to work for a direct connection as explained in Step 2 method 1.
//save this code into a file called Test.java and compile it |
If this program compiles and runs successfully, you should see some pretty boring output:
|
While that may not seem like much, let's take a quick look at what we've accomplished in the code.
- First, we set the DriverManager to understand ODBC data sources.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); - Then, we got a connection via the DSN as per Step 2 method 2:
We could have used the direct method instead to get our connection.String dataSourceName = "mdbTEST"; String dbURL = "jdbc:odbc:" + dataSourceName; Connection con = DriverManager.getConnection(dbURL, "","");
- Next, we created a
java.sql.StatementObject so we could run some queries:Statement s = con.createStatement();
- Then came the exciting stuff - we ran some queries and made some changes!
s.execute("create table TEST12345 ( column_name integer )"); // create a table s.execute("insert into TEST12345 values(1)"); // insert some data into the table s.execute("select column_name from TEST12345"); // select the data from the table - The next part might be a little strange - when we ran our select query (see above), it produced a
java.sql.ResultSet. A ResultSet is a Java object that contains the resulting data from the query that was run - in this case, all the data from the column column_name in the table TEST12345.ResultSet rs = s.getResultSet(); // get any ResultSet that came from our query if (rs != null) // if rs == null, then there is no ResultSet to view while ( rs.next() ) // this will step through our data row-by-row { /* the next line will get the first column in our current row's ResultSet as a String ( getString( columnNumber) ) and output it to the screen */ System.out.println("Data from column_name: " + rs.getString(1) ); } - After that we just cleaned up our database by dropping (completely removing) the newly created table:
s.execute("drop table TEST12345"); - Lastly, we need to close the Statement and Connection objects. This tells the database that we are done using them and that the database can free those resources up for someone else to use. It is very important to close your connections - failure to do so can over time crash your database! While this isn't too important with a MS Access database, the same rules apply for any data base (like Oracle, MS SQL, etc.)
s.close(); // close the Statement to let the database know we're done with it con.close(); // close the Connection to let the database know we're done with it
As you can see, if the ResultSet object rs equals null, then we just skip by the entire while loop. But since we should have some data in there, we do this while ( rs.next() ) bit.
What that means is: while there is still data to be had in this result set, loop through this block of code and do something with the current row in the result set, then move on to the next row.
What we're doing is looping through the result set, and for every row grabbing the first column of data and printing it to the screen. We are using the method provided in the result set called getString(int columnNumber) to get the data from the first column in our result set as as String object, and then we're just printing it out via System.out.println.
We know that the data in our ResultSet is of type String, since we just built the table a couple of lines before. There are other getXXX methods provided by ResultSet, like getInt() and getFloat(), depending on what type of data you are trying to get out of the ResultSet. Please refer to the JSDK API for a full description of the ResultSet methods.
That's it!! Now you know the basics for connecting to a MS Access Database via JDBC!
If you found this useful, please vote for me!
| What I assume you already know | BACK TO TOP |
I assume you are familiar with database concepts. If you don't know anything about what a database is or what it is for, please take 5 minutes and read this description from Webopedia.
I do assume that you understand Java syntax to a degree, and that you are comfortable compiling and executing Java code. If not, please point your browser to the Java Tutorials provided by Sun Microsystems - they'll get you started.
If you found this useful, please vote for me!