How to make a connection with a mySql database by using Java?

To do this, the simplest way is to use a JDBC driver :

  1. Downlaod the integral API from here.
  2. Put it in the /lib of your Tomcat installation folder if you want to use it in a web project or any folder accessible in your hard disk
  3. Right click on your project in Eclipse > Properties > Java Build Path > Add External JARs… > Choose the jar :  mysql-connector-java-5.1.16-bin.jar from the installation folder > OK. the jar will appear in the build path. Click on OK.
  4. Use the following code in your method :
    private static final String connectionString =”jdbc:mysql://IP_OR_NAME_SERVER;DatabaseName=DATABASE_NAME;user=USER;password=PWD“;
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    List<Person> usersList = new ArrayList();
    try{  Class.forName(“com.mysql.jdbc.Driver”);
    conn = DriverManager.getConnection(connectionString);
    stmt = conn.createStatement();
    String sqlQuery=”YOUR_QUERY_HERE “; // You put here your query : SELCET, UPDATE, DELETE, INSERT
    rs = stmt.executeQuery(sqlQuery); // If it is a SELECT QUERY e.g sqlQuery=”SELECT user,email FROM user”;
    while ( rs.next() ){ // To get data from result
    Person user = new Person();          user.setName(rs.getString(“user”));          user.setEmail(rs.getString(“email”));
    stmt.executeUpdate(sqlQuery); // If it is an UPDATE, DELETE or INSERT QUERY
    } catch (Exception e) {
    }finally {
    if (rs != null)                   try { rs.close(); } catch (Exception e) { //LOGGER}
    if (stmt != null)                   try { stmt.close(); } catch (Exception e) {//LOGGER }
    if (conn != null)                   try { conn.close(); } catch (Exception e) {
    //LOGGER}      }
  5. Congratulation… You made a connection with your mySql database by using JAVA and JDBC.

See also :

Share it with your freinds on Facebook Tweet it to your freinds on Twitter Myspace Friendfeed Technorati del.icio.us Digg Google Yahoo Buzz StumbleUpon

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

WP SlimStat