Imran's personal blog

January 28, 2011

Mysql from Java in Eclipse on a mac

Filed under: Uncategorized — ipeerbhai @ 1:21 am

The MySQL and Java documentation is pretty good, but takes too long to read. I’ve broken it down into steps.

Steps

1. Download Connector/J from MySQL.
2. Mount the disk image you just downloaded, extract the mysql-connector-(VERSION) JAR file.
3. Copy the JAR file to your resources folder on disk for your Java project.
4. Refresh your resources folder in Eclipse.
5. Add the JAR file to your build paths.( Control click the JAR file in your resources folder –> click “Add to build Path” )
6. Add the JDBC API imports to your Code.
a. import java.sql.*

7. Initialize Connector/J from the JDBC API.
a. In the function you want to access Mysql, add the following lines:
Connection con; // The JDBC provided connection object.
try {
Class.forName(“com.mysql.jdbc.Driver”).newInstance(); //instantiate the JDBC framework within Java

8. Establish a database connection.
a. Still in the try block:
con = DriverManager.getConnection(“jdbc:mysql://SERVER/DATABASE”, “USERNAME”, “PASSWORD”); // Ask the framework to make a connection and give me a connection reference. ( default TCP port 3306 )
if ( con.isClosed() )
return; // No database connection could be established.

9. Run a query and get a result set.
a. Still in try block
Statement sqlStatement = con.createStatement(); // Init the JDBC Statement object
ResultSet sqlResults = sqlStatement.executeQuery(“YOUR SELECT STATEMENT”); // Executes the select statement and puts the results in the resultset.

10. Parse the result set for the data you want.
a. Still in the try block
while( sqlResults.next() {
JavaType myDataInJava = sqlResults.getJavaType(“FIELDNAME”); // note, when I write “JavaType, I mean things like int, String, etc… )
// Do whatever you want with the data
}

Viola! you are now cooking with Java and MySQL!

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: