Saturday, October 11, 2008

JDBC Connection to mySQL in Application Tomcat Step 16A

One way to connect to the database is by connecting within your application.

Make sure you have downloaded the mysql driver from: http://dev.mysql.com/downloads/connector/j/5.1.html


If you are connecting to another database, you need to make sure you download the driver for that particular database.

Put the driver in the tomcat/common/lib directory.


Add this method to your userAction class or the class you are using to connect.

public Connection getConnection(String username, String password,String database, String server) 
throws Exception { 
Connection connection = null; 
try { String driverName = ""; 
String url = "jdbc:mysql://"+ server +"/"+ database; driverName = "com.mysql.jdbc.Driver"; Class.forName(driverName).
newInstance(); // Create a connection to the database connection = DriverManager.getConnection(url, username, password); 
catch (Exception e) { // Could not connect to the database System.out.println("error getting access to database " e); return null; } 
return connection; 
}



You can put this code in the setUser method in our UserAction.java class to test your connection.


Connection connection=getConnection("UserBook","UserBook123","catalog","localhost");

String sql="select BookName from book";

PreparedStatement ps=null;
ps=connection.prepareStatement(sql);
ResultSet set=ps.executeQuery();

while(set!=null&&set.next()) {
System.out.println(set.getString("BookName")); }
connection.close();

This code gets your connection, queries your book table and displays all the booknames within your book table. You can check your console to see if the name of the books printed out to know that you accessed your database correctly.

Go To Hibernate Step 16C

2 comments:

Rory November 1, 2008 2:36 PM  

Thanks for this, I am enjoying your blog, very helpful for my own setup (eclipse, mysql, struts, hibernate) Used the getConnection code here to replace my context.xml setup once I figured out it wouldn't work with godaddy. One suggestion would be working with a smaller font, or perhaps a slightly wider column layout. Maybe put this whole tutorial into a single pdf would be nice as well. Either way, keep blogging!

Greg November 3, 2008 6:30 PM  

Thanks for you comment. I am glad you found my code helpful. I will consider your recommendations to improve my blog.