Software >> Development >> Languages >> Java >> Examples >> How to connect to MySQL database

1. Obtain MySQL Connector/J (eg. mysql-connector-java-5.0.3-bin.jar) 2. Copy it into c:\program files\jre1.5.0\jre\lib\ext 3. write ConnMysql.java ---------------------------------------------------------------- import java.lang.String; import java.lang.Object; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.ResultSet; public class ConnMysql { public static void main(String args[]) { Connection con = null; ResultSet rs = null; try { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=somepassword"); } catch(ClassNotFoundException e) { System.err.println("ClassNotFoundException: " e.getMessage()); } catch(InstantiationException e) { System.err.println("InstantiationException: " e.getMessage()); } catch(IllegalAccessException e) { System.err.println("IllegalAccessException: " e.getMessage()); } rs = con.createStatement().executeQuery("SELECT VERSION()"); rs.next(); System.out.println(rs.getString(1)); } catch(SQLException e) { System.err.println("SQLException: " e.getMessage()); System.err.println("SQLState: " e.getSQLState()); System.err.println("VendorError: " e.getErrorCode()); } finally { try { if(con != null) con.close(); } catch(SQLException e) {} } } } ------------------------------------------------------------- 4. complile .java to .class javac -classpath . ConnMysql.java 5. run the class file java -classpath . ConnMysql