Monday, September 9, 2013

JDBC : 02 - JDBC First Example


JDBC First Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
* @author sanjeeva
* This example illustrate how to connect to a MySQL database and retrieve data from the DBUSER table
*/
public class DBConnection {

         Connection connection = null;

         public static void main(String args[]){
               DBConnection dbConnection = new DBConnection();
               dbConnection.createConnection();
         }

         private void createConnection(){
               Statement statement = null;
               ResultSet rs = null;
               String selectSQL = "SELECT USER_ID, USERNAME from DBUSER";
               try {
                     Class.forName("com.mysql.jdbc.Driver");
                     String username = "root";
                     String password = "res13pg";
                     connection = DriverManager .getConnection("jdbc:mysql://localhost:3306/myworkspace",username,password);

                     if(null != connection){
                            statement = connection.createStatement();
                            rs = statement.executeQuery(selectSQL);

                            while (rs.next()) {
                                   String usrid = rs.getString("USER_ID");
                                   String usrname = rs.getString("USERNAME");

                                   System.out.println("userid : " + usrid);
                                   System.out.println("username : " + usrname);
                            }
                     }
               } catch (ClassNotFoundException e) {
                     e.printStackTrace();
               } catch (SQLException e) {
                     e.printStackTrace();
               } finally {
                     if (null != connection){
                         try {
                               connection.close();
                         } catch (SQLException e) {
                               // TODO Auto-generated catch block
                               e.printStackTrace();
                         }
                    }
               }
       }

}


Output as follows :

userid : 101
username : Sanjeeva
userid : 102
username : Sandamali
userid : 103
username : Thinuli