|
February 2004 Technical Tip – Accessing MySQL Databases from
Java
Last month I
showed you how to set up and use MySQL. This month I will show you how to
access MySQL databases from Java. I will provide a complete, working
program. This is not intended to be a complete lesson on JDBC (as
provided in our
Java course), but only to provide the details of how to connect to a
MySQL database. Furthermore, I will assume the reader is making use of
IBM's WebSphere Studio Application Developer (WSAD) which is the IDE used
by most of our clients.
Getting MySQL Connector
Starting the MySQL server
- Start the MySQL server as discussed last month. Recall
that we opened a command prompt window and entered the commands
cd\minixampp and mysql_start.bat
- Recall that you must not close the window while the MySQL server is
running (you can minimize it, but do not close it.)
- If you do not start MySQL, you will get an exception when you try to
connect to the database:
java.sql.SQLException: Unable to connect
to any hosts due to exception: java.net.ConnectException: Connection
refused: connect
- You will, of course, need to create the database and table. We will
use database mydatabase, table mytable shown in last month's article.
Adding the JAR file to the build path
- Start WSAD.
- Right click on your Project and from its pop-up menu, select
Properties.
- In the Properties dialog, select the Java Build Path page.
- Click the Libraries tag.
- Click the Add External JARs button.
- In the dialog that appears, select the JAR file:
c:\mysql-connector-java-3.0.9-stable-bin.jar
JDBC example
- Key statements:
private static final String DRIVER =
"com.mysql.jdbc.Driver";
private static final String SOURCE =
"jdbc:mysql://localhost/mydatabase";
- Go to http://www.caliberdt.com/tips/JdbcWithMySQL.java
to see full source for a program which reads the table created in last
month's article.
Go to the articles index. Written
by Bill Qualls. Copyright © 2004 by Caliber Data Training
800.938.1222 |