Pages

Tuesday 8 January 2008

Connecting to a database

OK, I am very sure that you are very bored stiff by my lack of enthusiasm for serious stuff. I have trumpeted a lot on Java without giving out real stuff. OK, i admit I have been a failure there and you have me. I am now serious and ready to get my hands dirty, are you? Remember, I am not "that" experienced in Java programming so please bear with me.

OK, let's start with Database connectivity. I will use a MySQL database for this session(I always use MySQL). Firstly, you will need to have a MySQL database server installed on your system(Either locally or remotely, but accessible. I use a local connection i.e. the database server runs on my desktop). After downloading and installing your database server(I use MySQL 5.04; you can still download the latest.) You should also download the MySQL/ Java Database driver. This will enable you, through JDBC(Java Database Connectivity) to connect to the MySQL server from your applications(whether desktop or web or network) and issue queries directly or indirectly through an application server or web server ( two tier and three tier models respectively). In MySQL, the database driver is called the Connector/J. The last time I checked, the latest version was 5.0.. something.

With all that set, you should now install the MySQL driver into your system. Find the install directory of your Java platform. On Windows, it usually (by default) is C:\Program Files\Java.
Then locate the Java Runtime Environment (JRE) directory. Open it, the search for the 'lib' subdirectory. With that opened, search for 'ext' directory. Then, after extracting the files of your MySQL database driver, copy the something like mysql-connector-bin.jar(This is not the exact name but is something like it) file and paste it in the 'ext' sub-directory. With that under your belt, ladies and gentlemen, you have successfully installed your driver.

On to serious things; coding:
To test whether your driver is functioning; try out this code. It should give you results in your command line:

//TryOut.java

import java.sql.*;

public class TryOut
{
public static void main(String[] args)
{
Connection con;

System.out.println("Trying to load database driver");
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Successfully loaded MySQL database driver!");
}
//This exception indicates that the driver was not detected.
catch (ClassNotFoundException ex)
{
System.out.println(ex.getMessage());
}

System.out.println("Now connecting to database");
try
{
//Assuming that you have a MySQL database named 'menagerie',
//a user name 'user' and a password 'password' for connecting to the database server
con = DriverManager.getConnection("jdbc:mysql://localhost/menagerie", "user", "password");
}
catch (SQLException sqlEx)
{
System.out.println("Failed to connect to database");
}
catch (Exception ex)
{
System.out.println("Other unidentified problem");
}
}
}



If the above code is successfully executed, the command line should display the following message;

Trying to load database driver
Successfully loaded MySQL database driver!
Now connecting to database.

Anything other than the above indicates that a problem exists. You should therefore try the whole process again.
Remember, the directory that you should paste your MySQL database driver on Windows should be something like: C:\Program Files\Java\jre1.6.0_02\lib\ext

Saving into a blob

I have noticed that many programmers especially those very much accustomed to programming in event driven languages like Microsoft's Visual Basic have a hard time extracting or saving stuff like images, word documents, PDFs and so on in Java. This is due to the profound differences in JDBC and OLE.

However, I have developed a simple solution that has worked well with MySQL Coonnector/J and of course MySQL database server. Here is the code;

File in = new File("C:/Duke.jpg");
int fileLength = (int) in.length();
InputStream streamFile = new FileInputStream(in);
pstmt.setBinaryStream(1, streamFile, fileLength);

and wala, that's it. pstmt is an established PreparedStatement.