|
|
Terms of Agreement:
By using this article, you agree to the following terms...
1) You may use
this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame.
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description. |
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!
How to manipulate a Microsoft Access Database via JDBC
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
SELECT statement to retrieve data
- an
INSERT statement to add data
- a
DELETE statement to remove data
- an
CREATE TABLE statement to build a new table
- a
DROP TABLE statement to destroy a table
This document goes at a pretty slow pace, so you may not need to cover every little detail here. If you are entirely new to JDBC, you shouldn't have too much trouble following along. So let's get going!
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
2) After we set up the DriverManager, we need to get a Connection
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:
In addition, please refer to the section at the end of this document:
The first thing we must do in order to manipulate data in the database is to be granted a connection to the database. This connection, referenced in the Java language as an Object of type 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:
class Test
{
public static void main(String[] args)
{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (Exception e) {
System.out.println("Error: " + e);
}
}
} //save this code into a file called Test.java and compile it |
Notice the TRY-CATCH block. The forName() method might throw a ClassNotFoundException. This really can't happen with the JDBC:ODBC bridge, since it's built in to the Java API, but we still have to catch it. If you compile and run this code, it's pretty boring. In fact, if it produces any output, then that means that you've encountered an error! But it shows how to get your DriverManager set.
We're now ready to try and get a connection to our specific database so we can start to run SQL statements on it!
One way to get a connection is to go directly after the MS Access database file. This can be a quick and easy way to do things, but I have seen this not work on some windows machines. Don't ask me why - I just know that it works sometimes and it doesn't others...
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:
import java.sql.*;
class Test
{
public static void main(String[] args)
{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// set this to a MS Access DB you have on your machine
String filename = "d:/java/mdbTEST.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end
// now we can get the connection from the DriverManager
Connection con = DriverManager.getConnection( database ,"","");
}
catch (Exception e) {
System.out.println("Error: " + e);
}
}
} //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!
Microsoft has provided a method to build a quick Jet-Engine database on your computer without the need for any specific database software (it comes standard with Windows). Using this method, we can even create a blank Microsoft Access database without having MS Access installed!
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
Now our data source is done! Here's a complete program showing how to access your new DSN data source:
import java.sql.*;
public class Test
{
public static void main(String[] args)
{
// change this to whatever your DSN is
String dataSourceName = "mdbTEST";
String dbURL = "jdbc:odbc:" + dataSourceName;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(dbURL, "","");
}
catch (Exception err) {
System.out.println( "Error: " + err );
}
}
} //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!
Once you have your connection, you can manipulate data within the database. In order to run a SQL query, you need to do 2 things:
- Create a Statement from the connection you have made
- Get a ResultSet by executing a query (your insert/delete/etc. statement) on that statement
Now lets learn how to make a statement, execute a query and display a the ResultSet from that query.
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.
import java.sql.*;
public class Test
{
public static void main(String[] args)
{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
/* the next 3 lines are Step 2 method 2 from above - you could use the direct
access method (Step 2 method 1) istead if you wanted */
String dataSourceName = "mdbTEST";
String dbURL = "jdbc:odbc:" + dataSourceName;
Connection con = DriverManager.getConnection(dbURL, "","");
// try and create a java.sql.Statement so we can run queries
Statement s = con.createStatement();
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
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) );
}
s.execute("drop table TEST12345");
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
}
catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
} //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:
String dataSourceName = "mdbTEST";
String dbURL = "jdbc:odbc:" + dataSourceName;
Connection con = DriverManager.getConnection(dbURL, "","");
We could have used the direct method instead to get our connection.
- Next, we created a
java.sql.Statement Object 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) );
}
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.
- 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
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!
This document assumes that you are working on a Windows machines since we'll be connecting to a Microsoft Access database.
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! | |
Other 2 submission(s) by this author
|
|
|
Report Bad Submission |
|
|
Your Vote! |
See Voting Log |
|
Other User Comments |
3/1/2002 3:58:26 PM:cdb8 Excellent article. I am 2 wks new to
Java. I was able to fully understand
and follow the steps outlined. Thanks
Jeff!
|
3/4/2002 9:07:01 AM:Jose M Serrano Good Article !!! 5 from me
|
3/20/2002 1:58:44 AM:Zebastion Great, keep up the good work dude!
|
3/20/2002 2:06:11 AM:Ken Very well done, thank you for speaking
plain english.
|
3/23/2002 10:19:50 AM:Tailgunner Great! I'll need for my university
project, thanks! 5 globes
|
3/24/2002 9:41:18 PM:pedro santana very good - keep up the good work!!
|
4/5/2002 3:45:17 AM:Ric. Very good article , thanks.
|
5/4/2002 4:33:17 AM:Sarfraz Ahmed Its perfect.I was searching these
things for many days.Tell me one
thing,can it run on jdk1.3.Please mail
me ahmed_pk82@hotmail.com
|
5/13/2002 8:00:39 AM:kulani I wrote a program to describe to
to
connect to Microsoft Access as you
decribed above but i got this
error
Java.sql.sqlException[Microsoft][
ODBC Driver Manager ]Data source name
not found and default driver specified
|
5/13/2002 8:24:41 AM:kulani I ve been trying to use JDBC to connect
to Microsoft Access as you described
above but i got this error
java.sql.sqlException [Microsoft][ODBC
Driver Manager]Data source name not
found and no default driver specified
please help,i am doing a project and i
am stuck,my project is due soon
|
6/5/2002 12:25:26 PM:pradeep well this is nice article for the
beginers who want to work with MS
Access
iam sure those people who want
to make such programme with MS Access
they will get most important tips from
this article
thanking you.
|
6/15/2002 3:37:24 AM:Sharif Really a nice article. I m very much
new to java and just know nothing about
JDBC. But it made me very confident to
work on DB using Java. Thanks a lot to
the Author !!!
|
7/2/2002 6:45:29 AM:suresh The way of explanation is very
good.Really new ones can easily go
through.
|
7/17/2002 11:57:01 PM:arvin hey the code is very good!! really i
can use this one, can i request you
something? can you give me a bean that
could connect to SQL server and the
output in JSP i know you can do it.
also example of add edit delete
appreciate it if you give me soon, you
can email me at arvinski@pinoymail.com
|
7/22/2002 12:57:34 AM:sam thanks to the author, you really give
me a big hand on this topic!!! but i
want to ask here is, is it possible i
use similar method to put database in
my applet? and the more frightening
thing is, how can i update and store it
? i wanna build up some database in
the game, after getting the score, it
would store it in a list.how can i do
that? thanks for regard.
P/s: I m not
quite understand
about
1. s.execute("create table
TEST12345 ( column_name integer )"); //
create a table
2. s.execute("insert
into TEST12345 values(1)"); // insert
some data into the
table
3. s.execute("select column_name
from TEST12345"); // select the data
from the table
where the table
TEST12345 we had created?
|
8/24/2002 5:14:29 PM:p.pradeep The best website i have ever found in
the
Net World .
|
9/5/2002 12:45:25 AM: Hi. Good article. I'm working on a
RMI project that need a DB. Since I
can't install any DB drivers I was
going to have my server save is datas
in XML format. With this, I now know
that I can, and may use, an Access DB
for this project. It will also give me
the oportunity to normalise the data a
little bit.
I still want to do a
XML-DB manager. But for now I don't
have the time.
Tanks.
|
9/19/2002 9:25:54 PM: when i compile the
|
9/22/2002 10:28:22 PM: VERY VERY GOOD,I USE IT IN MS
SQL200,AND PASS,
|
9/26/2002 5:53:40 AM: super concise, clear and detailed
explanation with encouraging
simplicity.
The author is one step
away of beating even the legendary
Peter Norton in simplicity.
|
9/26/2002 11:17:33 PM:Josh McCullough very nice, 5 from me!
|
10/18/2002 4:02:34 AM:Gareth Stretch great work, just starting out, it
helped alot thanks
|
10/20/2002 11:01:37 PM: Thats a great article, thks so much to
the author. As a beginner in java, I
find this very helpful and easy to
understand and this has helped my
project.
|
10/20/2002 11:45:29 PM: Thanks Jeff It has helped me a lot
|
11/2/2002 2:32:30 PM: I found an error during the process of
compiling my application..
|
11/2/2002 2:43:04 PM: I was working with an application that
uses JDBC-ODBC bridge and I had
problems.. the message was
"[Microsoft][JDBC-ODBC Driver for
Microsoft Access]Degree of derived
table does not match column list" What
can I do? Can you help me?
|
11/22/2002 1:59:31 PM: Excellent! I was running queries
within an hour! Thank you!
|
12/27/2002 11:51:24 AM: Very concise article. i spent 3 days
prior to reading this article to
connect to an access database. I
managed to do in in under 10 minutes
with the help of this article. Thanks
|
1/3/2003 6:44:07 PM: Concise yet complete - thanks!
|
1/16/2003 8:25:44 PM: This code was very usefull now I do not
need to use my c++ code to access the
db. I am currently building a project
which communicates via serial port to a
cnc, this code makes it alot easyer
for me to maintain file address table
for storage and retrieval. In closing
I have tryed to get this table info for
quite some time. Thank you and keep up
the excellent work.
|
1/16/2003 9:59:55 PM: Additional SQL statements can be found
@
http://www.geocities.com/SiliconValle
y/Vista/2207/sql1.html
|
2/18/2003 9:50:29 PM:
|
2/18/2003 9:54:59 PM: String aa="INSERT INTO PRODUCT
VALUES("+a1.getText()+","+a2.getText()+"
,12.50,25.75,5000)";
stmt.executeUpdate
(aa);
THERE IS
ERROR:
java.sql.SQLException:
[Microsoft][ODBC Microsoft Access
Driver] Too few parameters. Expected 2.
|
2/27/2003 8:11:34 PM: Really helpful and clear.
|
4/3/2003 1:10:42 AM: Brilliant article. You should
definitely go into teaching!
|
4/5/2003 8:49:46 PM: I´m sorry, but i couldnt vote for you,
because i get a login and the
validation aplication didn´t let me to
the log. I try it 3 times and always an
error message stating page not found
apears. never the less i´ll give you
for the help that this code gave to me
5 stars.Thank you.
|
4/28/2003 11:32:07 AM:levissimard Perfect article, Really helpful and
clear. Thanks
|
4/30/2003 1:17:06 PM: briliant article.just fabulous
|
5/16/2003 8:32:35 AM: Jeeez, it provided me with everything I
needed, and could not find pouring over
200 pages of jdbc
specification.
Clean, straight to the
point, and simple.
Keep it like this
:)) Good job :)
|
5/19/2003 3:51:49 AM: Excelent!
That's that I needed to
start programming in JAVA.
THANKS!
|
5/26/2003 10:23:41 AM: While your code is useful, it would
have been nice for you to tackle what
is seemingly the most difficult portion
of Java and Access, Date functions.
|
6/2/2003 1:32:32 PM: U help me to have a good start on
Database with Java from this good
example.... : )
|
6/7/2003 10:27:17 PM: Absolutely fantastic article! I wish
more people would contribute their
knowledge so clearly and freely. You
should be a teacher!
|
7/1/2003 3:57:54 PM: Beautiful article. I have been using
JDBC for several months with Oracle; it
is nice to see it proven that the same
techniques will work equally well on
the smaller scale.
|
7/4/2003 4:36:46 PM: Jeff....you've done it man. I was
struggling with my project on database
connectivity but your straight forward
approach done it. Thumbs
up.
madmax2@excite.com
|
7/31/2003 12:35:58 AM: Nice tutorial. Hope u can submit a
downloadable form as Word document,pdf
or etc.
|
8/3/2003 3:19:47 AM: Thank you.you are the best.
|
8/18/2003 3:44:17 AM: yes!!! that very nice code but how if
that every time i run this program and
the database table already create like
your code below :
s.execute("create
table TEST12345 ( column_name integer
)");
that will be the problem that
because the table already exits in the
database right?
so before the coding
of create a new table u should code a
statement for or something else that to
check whether the table is exit or not
right? ^_^
i know u can improve your
code ...
|
10/1/2003 4:07:55 PM:Dilshan Jesook Ever think of writing a book? you got
what it takes. By the way any one knows
how to connect to a MS SQL DB ?
|
10/2/2003 3:52:17 AM: This stuff was really useful to me and
my friends. Thanks a lot. keep it up
|
10/10/2003 8:47:54 AM:Royscki tnx! you helped me a lot dude.
|
11/19/2003 2:57:54 PM: Good one..indeed!
|
|
Add Your Feedback! |
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.
NOTICE: The author of this article has been kind enough to share it with you. If you have a criticism, please state it politely or it will be deleted.
For feedback not related to this particular article, please click here. |
|