Java Tutorial

From Hashmysql
Jump to: navigation, search

Java and MySQL

This document is only meant to get you started with connecting to a MySQL Database with Java and JDBC. The documentation on the MySQL Site is quite thorough and should definetly be read: MySQL Connector/J Basics

Getting MySQL Connector/J and Installing

To connect to mysql with Java, you will need the MySQL Connector/J from the MySQL AB Site.

Download it at: MySQL Connector/J Download

To be able to use the Connector/J as a JDBC Driver, you'll have to add the included mysql-connector-java-*-bin.jar to your Java Class Path.

We are no ready to use JDBC and the MySQL Connector/J Driver.

A Simple Example

   import java.sql.*
   ....class definition....
   Statement stmt;
   ResultSet rs;
   try {
       Class.forName("com.mysql.jdbc.Driver").newInstance();
   } catch (Exception ex) {
       System.out.println(ex);
   }  
   try {
       String myUrl = "jdbc:mysql://yourserver.comOrYourIP/databaseName?user=yourUser&password=yourPassword";
       Connection conn = DriverManager.getConnection(myUrl);
       stmt = conn.createStatement();
       String query = "SELECT * FROM table WHERE column LIKE '%test%'"; 
       rs = stmt.executeQuery(query); 
       while (rs.next()) { 
           String s = rs.getString("field1"); 
           String d = rs.getDate("field2"); 
           System.out.println(s + " " + n); 
       }
   } catch (SQLException ex) {
       System.out.println("SQLException: " + ex.getMessage());
       System.out.println("SQLState: " + ex.getSQLState());
       System.out.println("VendorError: " + ex.getErrorCode());
   }

Notes

Remember you should always close your resources after you are done with them.

For an example on closing your resources, check the examples on these pages:

Closing Result Resources and Statements

Closing Statements and Connections (uses Connection Pooling instead of regular Connection Handling with DriverManager)

The use of Connection Pooling is STRONGLY recommended. This way you don't need to instanciate a Connection for each connection to the MySQL Server, and you also don't need to close each connection.

More Information on Connection Pooling:

Sun Connection Pool Tutorial


Links

If you're still having troubles, try these links:

Sun JDBC Tutorial

MySQL Connector/J Documentation