February 27, 2013

A Program that connects to MySql DB using JDBC

To Install MySql on ubuntu, is pretty staright forward
1. either search mysql in ubuntu software center
         or
2. Install from shell/bash/command-line like below
sudo apt-get update && sudo apt-get upgrade
sudo apt-get install mysql-server mysql-client

To Start in MySql as root(for starting it 1st time, it'll ask for password) -
mysql -u root -p   
Have a look at what DB and Tables you already have or may be create one
show databases;
show tables;
CREATE DATABASE NewDB 
Choose a DB:
use NewDB 

Now download the MySql JDBC ConnectorJ driver from here
Extract the downloaded ConnectorJ.tar file in some folder and find mysql-connector-java-someversion- bin.jar there.
This jar has to be added as classpath in eclipse.
To do this from eclipse's, project > right click > properties > java build path > libraries > add external jars > find the above mentioned jar in your system > press ok.
once done you can find find the above mentioned mysql-connector.jar file inside your project > java resource > libraries

Few things to note:
MySql username - you can find this by passing select user(); on mysql client(i.e from bash > mysql - u root -p > select user();)
  In my system, username is - root
Password - which you know already from the time you started MySQL
Very important: the default mysql url = jdbc:mysql://localhost:3306/dbName


Now Lets see some code

public class DBTest {

 public static void main(String[] args) {
  try{
   runTest();
  }catch(SQLException ex){
   for(Throwable t : ex){
    t.printStackTrace();
   }
  }catch (IOException e) {
   e.printStackTrace();
  }
 }

 public static void runTest() throws SQLException, IOException {


  /*here i m getting  connection with help from DriverManager class,
   * what it does is it iterates through registered drivers to find
   * the driver that can be used with 'the sub-protocol' specified
   * in url
   * Note - sub-protocol is what you see after "jdbc:"
   *      - locahost will be consistent cos i am testing this with
   *       bind-address as "127.0.0.1"
   *      - 3306 is default port of mysql,
   *          which can be changed in etc/mysql/my.cnf
   *      - MyDB is database that i created in mysql
   *      - root is the user name, where as **** is password for mysql
   *  */

  Connection conn = DriverManager.getConnection
         ("jdbc:mysql://localhost:3306/MyDB", "root", "****");
  try {
   Statement stat = conn.createStatement();
   stat.executeUpdate("CREATE TABLE FRIENDS (NAME CHAR(20))");
   stat.executeUpdate("INSERT INTO FRIENDS VALUES('MARK')");
   stat.executeUpdate("INSERT INTO FRIENDS VALUES('WONG')");
   stat.executeUpdate("INSERT INTO FRINEDS VALUES('SARAH')");
   
   ResultSet result = stat.executeQuery("SELECT * FROM FRIENDS");
   for(int x = 1; x <= 3; x++){
    if(result.absolute(x)){
     System.out.println("" + x + ": "+ result.getString(1));
    }
   }
   result.close();
                        stat.executeUpdate("DROP TABLE FRIENDS");
  }finally{
   conn.close();
  }
 }
}

0 comments:

Post a Comment