aspose file tools*
The moose likes JDBC and the fly likes Single class file to handle connect/disconnect methods for a MySQL database Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Single class file to handle connect/disconnect methods for a MySQL database" Watch "Single class file to handle connect/disconnect methods for a MySQL database" New topic
Author

Single class file to handle connect/disconnect methods for a MySQL database

Xuxo Garcia
Greenhorn

Joined: Feb 07, 2012
Posts: 3

Hi,

I will first admit to being new to java coding. Recently, I decided to finally sit down and train myself in the language.

As part of my self-imposed assignment I am building a webapp using a MySQL back-end. A while back, I had built this on a PHP/nuSOAP/MySQL design and now I want to replicate in Java. The architecture for the original design had the following:

1) Relational Database (MySQL 5.1)
2) PHP global variables (to re-use without having to re-write a lot)
3) Central PHP functions file
4) SOA functions file with WSDL creation
5) PHP front end which interacted with the functions file

In Java, I have:

1) Same Database
2) config.properties file with things like (dbuser, dburl, dbpassword, dbdriver, etc.)
3) dbConnection class

Now, I can connect to the database using the following code:



This works as I am able to get the "Database connection established" message in the console. But what I want this class to do is to call two methods that I can access from an external java client (to be constructed):

- dbConnect()
- dbClose()

In this fashion, I can have an external client call 'dbConnect()' and connect to DB, perform SQL queries, call stored procedures, and all that good stuff... and then call 'dbClose()' when is all done! For me, in PHP, this was a very modular approach to handle the database connections from a different functions' file.

The source code above is divided on two sections "SECTION A and SECTION B". Section A is the connection code and SECTION B. The latter is what I need help on. I was thinking about enclosing my SECTION A under a 'public static dbConnect()' and SECTION B to be a 'public static dbClose()'. However, how would I close a connection on a separate method?

Any advice on how to create this 'connection manager'? Thanks in advance


Wendy Gibbons
Bartender

Joined: Oct 21, 2008
Posts: 1107

take the code out of main, in fact delete the main method and create 2 methods I would call one getConnection and close
so your code would go



the advantage of this solution is you can alomst seemlessly add in connection pooling if you want to.
Xuxo Garcia
Greenhorn

Joined: Feb 07, 2012
Posts: 3

You rock!!!...thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Single class file to handle connect/disconnect methods for a MySQL database