Wednesday 5 September 2012

Connecting Java and MySQL


As you all know Java is one of the best programming languages around and MySQL is the world’s most popular open source database. Often these are used to build business applications. There arises the need to connect both of these technologies. But for a newbie like me it is quite a daunting task to make them talk to each other. So, I am putting forward a tutorial showing how to accomplish the task.

I am assuming that the reader have installed both Java and MySQL.

First of all we need MySQL Connector/J driver. It is the official JDBC driver for MySQL. Which can be downloaded from  http://dev.mysql.com/downloads/connector/j/ .Moreover I have enclosed the driver used for this tutorial.

It was the easy part. Now the most confusing part if you don’t know how to set classpath. Classpath can be set in more than one way. I shall use the method which I prefer the most.

The file name of the MySQL Connector/J driver I have downloaded is

mysql-connector-java-5.1.11-bin.jar

I have kept this file in C:\Program Files\Java\jdk1.6.0_12\lib in my system. You can place it anywhere you like.

JAR file (or Java ARchive) collection of many files into one. Java developers generally use .jar files to distribute Java applications or libraries, in the form of classes and associated metadata and resources. In this case mysql-connector-java-5.1.11-bin.jar file contains all the classes required for Java, MySQL connection.



Now I shall set the classpath so that our program can use this library to connect the MySQL database.

Click Start or the Windows icon in the bottom left corner of your screen. Then Select Computer, Properties.

jmcimg1.jpg


Now Select Advanced System Settings
jmcimg2.jpg

Select Environment Variable in the System Properties Window


 jmcimg3.jpg

Choose ClassPath from the System Variable Pane and click Edit Button.

jmcimg4.jpg


Enter the Path of mysql-connector-java-5.1.11-bin.jar file after putting a semicolon in case there are previous settings. In most cases there you would find some. Click Ok couples of time. That’s all.  You have set the classpath. In some instances you might have to restart your system.
Now we shall write the code to connect MySQL database.



import java.sql.*;

public class TestConnection{
  public static void main(String[] args) {
    System.out.println("MySQL Connect Example.");
    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "test";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root";
    String password = "";
    try {
      Class.forName(driver).newInstance();
      conn = DriverManager.getConnection(url+dbName,userName,password);
      System.out.println("Connected to the database");
      conn.close();
      System.out.println("Disconnected from database");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
mysql-connector-java-5.1.11-bin.jar is the best as i am connnected with it with the latest version am facing some issues will post after correcting them......
Thank you guys............Stay tuned !!!!!!!!

Sunday 2 September 2012

Send HTTP request & fetching data using Java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
 
public class Main {
    public static void main(String[] args)  {
        try {
            URL my_url = new URL("http://www.vikram-programmingwithjava.blogspot.in");
            BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));
            String strTemp = "";
            while(null != (strTemp = br.readLine())){
            System.out.println(strTemp);
        }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Connecting to Oracle using Java JDBC

import java.util.*;
import java.sql.*;

public class OracleJdbcTest
{
    String driverClass = "oracle.jdbc.driver.OracleDriver";

    Connection con;
     
    public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException
    {
        Properties props = new Properties();
        props.load(fs);
        String url = props.getProperty("db.url");
        String userName = props.getProperty("db.user");
        String password = props.getProperty("db.password");
        Class.forName(driverClass);

        con=DriverManager.getConnection(url, userName, password);
    }
     
    public void fetch() throws SQLException, IOException
    {
        PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");
        ResultSet rs = ps.executeQuery();
         
        while (rs.next())
        {
            // YOUR LOGIC
        }
        rs.close();
        ps.close();
    }

    public static void main(String[] args)
    {
        OracleJdbcTest test = new OracleJdbcTest();
        test.init();
        test.fetch();
    }
}