Saturday, October 22, 2011

Sample JDBC Program

Download mysql-connector-java-5.1.12-bin.jar. Include mysql jar in your project. (Go to Eclipse Menu 'Project -> Properties -> Java Build Path -> Libraries -> 'Add External JARs' add downloaded jar)
package testJdbcPackage;

import java.sql.*;

public class TestJdbc {
 
 Connection conn;
 
 public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
  new TestJdbc();
 }
 
 public TestJdbc() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
  String url = "jdbc:mysql://localhost/test";
  String user = "root";
  String password = "mysql";
  try {
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   conn = DriverManager.getConnection(url, user, password);
   doInsertTest();
   doDeleteTest();
   doInsertTest();
   doSelectTest();
  } catch (SQLException e) {
   e.printStackTrace();
  }  
 }
 
 private void doDeleteTest() {
  try {
   Statement statement = conn.createStatement();
   //Get the count
   ResultSet rs = statement.executeQuery("SELECT COUNT(1) FROM student");
   int recordCount = 0;
   while(rs.next()) {
    recordCount = rs.getInt("COUNT(1)");
   }
   rs.close();
   if (recordCount > 1) {
    recordCount -= 1 ;
   }
   boolean defaultAutoCommit = conn.getAutoCommit();
   conn.setAutoCommit(false);
   try {
    statement.executeUpdate("DELETE from student LIMIT " + recordCount);
    conn.commit();
   } catch (Throwable e) {
    conn.rollback();
   } finally {
    conn.setAutoCommit(defaultAutoCommit);
   }   
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
 }

 private void doSelectTest() {
  Statement statement;
  try {
   statement = conn.createStatement();
   ResultSet rs = statement.executeQuery("SELECT * from student");
   while(rs.next()) {
    int columnCount  = rs.getMetaData().getColumnCount();
    for (int i = 1; i <= columnCount; i++) {
     System.out.println(rs.getObject(i));
    }
   }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }    
 }

 private void doInsertTest() {
  Statement statement;
  try {
   statement = conn.createStatement();
   statement.executeUpdate("INSERT INTO student(name, status, deleted) VALUES('Gubs', 'active', 0)");
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }    
 }
}

No comments :

// Below script tag for SyntaxHighLighter