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();
    }
}

Sunday, 26 August 2012

Java and My Sql datatypes


The following table represent the default Java mapping for various common MySQL data types:
MySQL Type
Java Type
CHARString
VARCHARString
LONGVARCHARString
NUMERICjava.math.BigDecimal
DECIMALjava.math.BigDecimal
BITboolean
TINYINTbyte
SMALLINTshort
INTEGERint
BIGINTlong
REALfloat
FLOATdouble
DOUBLEdouble
BINARYbyte []
VARBINARYbyte []
LONGVARBINARYbyte []
DATEjava.sql.Date
TIMEjava.sql.Time
TIMESTAMPjava.sql.Tiimestamp
  1. CHAR, VARCHAR and LONGVARCHAR
    MySQL data types CHAR, VARCHAR, LONGVARCHAR are closely related. CHAR represents a small, fixed-length character string, VARCHAR represents a small, variable-length character string, and LONGVARCHAR represents a large, variable-length character string. There is no need for Java programmer to distinguish these three MySQL data types. These can be expressed identically in Java. These data types could be mapped in Java to either String or char[]. But String seemed more appropriate type for normal use. Java String class provide a method to convert a String into char[] and a constructor for converting a char[] into a String.
     
    The method ResultSet.getString allocates and returns a new String. It is suitable for retrieving data from CHAR, VARCHAR and LONGVARCHAR fields. This is suitable for retrieving normal data, but LONGVARCHAR MySQL type can be used to store multi-megabyte strings. So that Java programmers needs a way to retrieve the LONGVARCHAR value in chunks. To handle this situation, ResultSet interface have two methods for allowing programmers to retrieve aLONGVARCHAR value as a Java input stream from which they can subsequently read data in whatever size chunks they prefer. These methods are getAsciiStream andgetCharacterStream, which deliver the data stored in a LONGVARCHAR column as a stream of ASCII or Unicode characters.
      
  2. NUMERIC and DECIMALThe NUMERIC and DECIMAL MySQL data types are very similar. They both represent fixed point numbers where absolute precision is required. The most convenient Java mapping for theseMySQL data type is java.math.BigDecimal. This Java type provides math operations to allowBigDecimal types to be added, subtracted, multiplied, and divided with other BigDecimaltypes, with integer types, and with floating point types.

    We also allow access to these MySQL types as simple Strings and char []. Thus, the Java programmers can use the getString() to retrieve the NUMERICAL and DECIMAL results.
     
  3. BINARY, VARBINARY and LONGVARBINARY 
    These MySQL data types are closely related. BINARY represents a small, fixed-length binary value, VARBINARY represents a small, variable-length binary value and LONGVARBINARYrepresents a large, variable-length binary value. For Java programers there is no need to distinguish among these data types and they can all be expressed identically as byte arrays in Java. It is possible to read and write SQL statements correctly without knowing the exactBINARY data type. The ResultSet.getBytes method is used for retrieving the DECIMAL andNUMERICAL values. Same as LONGVARCHAR type, LONGVARBINARY type can also be used to return multi-megabyte data values then the method getBinaryStream is recommended.
     
  4. BITThe MySQL type BIT represents a single bit value that can be 'zero' or 'one'. And this MySQLtype can be mapped directly to the Java boolean type.
      
  5. TINYINT, SMALLINT, INTEGER and BIGINT
    The MySQL TINYINT type represents an 8-bit integer value between 0 and 255 that may be signed or unsigned. SMALLINT type represents a 16-bit signed integer value between -32768 and 32767. INTEGER type represents a 32-bit signed integer value between -2147483648 and 2147483647. BIGINT type represents an 64-bit signed integer value between -9223372036854775808 and 9223372036854775807. These MySQL TINYINT, SMALLINT, INTEGER, and BIGINT types can be mapped to Java's byte, short, int and long data types respectively.
     
  6. REAL, FLOAT and DOUBLE
    The MySQL REAL represents a "single precision" floating point number that supports seven digits of mantissa and the FLOAT and DOUBLE type represents a "double precision" floating point number that supports 15 digits of mantissa. The recommended Java mapping for REALtype to Java float and FLOAT, DOUBLE type to Java double.
     
  7. DATE, TIME and TIMESTAMP
    These three MySQL types are related to time. The DATE type represents a date consisting of day, month, and year, the TIME type represents a time consisting of hours, minutes, and seconds and the TIMESTAMP type represents DATE plus TIME plus a nanosecond field. The standard Java class java.util.Date that provides date and time information but does not match any of these three MySQL date/time types exactly, because it has DATE and TIME information but no nanoseconds.
    That's why we define three subclasses of java.util.Date. These are:
     
    • java.sql.Date for SQL DATE information.
    • java.sql.Time for SQL TIME information.
    • java.sql.Timestamp for SQL TIMESTAMP information. 

Java with MySql


1. Java Database Connectivity (JDBC)

The interface for accessing relational databases from Java is JDBC. Via JDBC you maintain the databases connection, issue database queries and updates and receive the results.
JDBC is an interface independently of any database. For each database you require the database specific implementation of the JDBC driver.

2. Introduction to MySQL

To learn to install and use MySQL please see MySQL - Tutorial.
The following will assume that you have successfully installed MySQL and know how to access MySQL via the command line.

3. MySQL JDBC driver

To connect to MySQL from Java you have to use the JDBC driver from MySQL. The MySQL JDBC driver is called "MySQL Connector/J". You should be able to find the latest MySQL JDBC driver on this pagehttp://dev.mysql.com/downloads/connector/j .
The download contains a jar file which we require later.

4. Create example database

Start the MySQL command line client and paste the following SQL script into it to create a sample database which we can use as an example.
create database feedback;
use feedback;
CREATE USER sqluser IDENTIFIED BY 'sqluserpw'; 
grant usage on *.* to sqluser@localhost identified by 'sqluserpw'; 
grant all privileges on feedback.* to sqluser@localhost;

CREATE TABLE COMMENTS (id INT NOT NULL AUTO_INCREMENT, 
    MYUSER VARCHAR(30) NOT NULL,
    EMAIL VARCHAR(30), 
    WEBPAGE VARCHAR(100) NOT NULL, 
    DATUM DATE NOT NULL, 
    SUMMERY VARCHAR(40) NOT NULL,
    COMMENTS VARCHAR(400) NOT NULL,
    PRIMARY KEY (ID));

INSERT INTO COMMENTS values (default, 'lars', 'myemail@gmail.com','http://www.vogella.com', '2009-09-14 10:33:11', 'Summery','My first comment'); 

5. Java JDBC

Create a Java project and a package "de.vogella.mysql.first".
Create a folder "lib" and copy the JDBC driver into this folder. Add the JDBC driver to your classpath. SeeAdding jars to the classpath for details.
Create the following class to connect to the MySQL database and perform queries, inserts and deletes. It also prints the metadata (table name, column names) of a query result.
package de.vogella.mysql.first;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

public class MySQLAccess {
  private Connection connect = null;
  private Statement statement = null;
  private PreparedStatement preparedStatement = null;
  private ResultSet resultSet = null;

  public void readDataBase() throws Exception {
    try {
      // This will load the MySQL driver, each DB has its own driver
      Class.forName("com.mysql.jdbc.Driver");
      // Setup the connection with the DB
      connect = DriverManager
          .getConnection("jdbc:mysql://localhost/feedback?"
              + "user=sqluser&password=sqluserpw");

      // Statements allow to issue SQL queries to the database
      statement = connect.createStatement();
      // Result set get the result of the SQL query
      resultSet = statement
          .executeQuery("select * from FEEDBACK.COMMENTS");
      writeResultSet(resultSet);

      // PreparedStatements can use variables and are more efficient
      preparedStatement = connect
          .prepareStatement("insert into  FEEDBACK.COMMENTS values (default, ?, ?, ?, ? , ?, ?)");
      // "myuser, webpage, datum, summery, COMMENTS from FEEDBACK.COMMENTS");
      // Parameters start with 1
      preparedStatement.setString(1, "Test");
      preparedStatement.setString(2, "TestEmail");
      preparedStatement.setString(3, "TestWebpage");
      preparedStatement.setDate(4, new java.sql.Date(2009, 12, 11));
      preparedStatement.setString(5, "TestSummary");
      preparedStatement.setString(6, "TestComment");
      preparedStatement.executeUpdate();

      preparedStatement = connect
          .prepareStatement("SELECT myuser, webpage, datum, summery, COMMENTS from FEEDBACK.COMMENTS");
      resultSet = preparedStatement.executeQuery();
      writeResultSet(resultSet);

      // Remove again the insert comment
      preparedStatement = connect
      .prepareStatement("delete from FEEDBACK.COMMENTS where myuser= ? ; ");
      preparedStatement.setString(1, "Test");
      preparedStatement.executeUpdate();
      
      resultSet = statement
      .executeQuery("select * from FEEDBACK.COMMENTS");
      writeMetaData(resultSet);
      
    } catch (Exception e) {
      throw e;
    } finally {
      close();
    }

  }

  private void writeMetaData(ResultSet resultSet) throws SQLException {
    //   Now get some metadata from the database
    // Result set get the result of the SQL query
    
    System.out.println("The columns in the table are: ");
    
    System.out.println("Table: " + resultSet.getMetaData().getTableName(1));
    for  (int i = 1; i<= resultSet.getMetaData().getColumnCount(); i++){
      System.out.println("Column " +i  + " "+ resultSet.getMetaData().getColumnName(i));
    }
  }

  private void writeResultSet(ResultSet resultSet) throws SQLException {
    // ResultSet is initially before the first data set
    while (resultSet.next()) {
      // It is possible to get the columns via name
      // also possible to get the columns via the column number
      // which starts at 1
      // e.g. resultSet.getSTring(2);
      String user = resultSet.getString("myuser");
      String website = resultSet.getString("webpage");
      String summery = resultSet.getString("summery");
      Date date = resultSet.getDate("datum");
      String comment = resultSet.getString("comments");
      System.out.println("User: " + user);
      System.out.println("Website: " + website);
      System.out.println("Summery: " + summery);
      System.out.println("Date: " + date);
      System.out.println("Comment: " + comment);
    }
  }

  // You need to close the resultSet
  private void close() {
    try {
      if (resultSet != null) {
        resultSet.close();
      }

      if (statement != null) {
        statement.close();
      }

      if (connect != null) {
        connect.close();
      }
    } catch (Exception e) {

    }
  }

} 
Create the following main program to test your class.
package de.vogella.mysql.first.test;

import de.vogella.mysql.first.MySQLAccess;

public class Main {
  public static void main(String[] args) throws Exception {
    MySQLAccess dao = new MySQLAccess();
    dao.readDataBase();
  }


}