Jan 31, 2010

How to connect SQL with JAVA?

JAVA and SQL Connection :

--------------------------------------------------------------------
Publicize Yourself ... Free!!!      Saalram.com
--------------------------------------------------------------------

    Java can do anything. Most of the realtime applications uses databases and they do connections via Java also. Let me explain how to make sql connection with java and an example.

First Import java.sql to get access to sql classes/methods.
    "import java.sql.*; "

Next need to identify the sql driver. Here i have used MySQL driver.
      " Class.forName("com.mysql.jdbc.Driver"); "

Then make sql connection with the help of driver manager.
    "Connection con= DriverManager.getConnection("jdbc:mysql://hostname/DB Name","DBUsername","DBPassword");  "

So we connected to DB now. Why do we need to connect database? It could be because to fetch/insert some sort of data into it. Let try to fetch some records from DB here. So i have to write a "select" query to get the appropriate data?

Then we have to execute that query from java. It can be possible with statement objects. Using statement objects we can execute the composed query to get result set.

        "   Statement stmt=con.createStatement();
           ResultSet rs=stmt.executeQuery("select Name,placeOfBirth,Batch from trainees_Details where traineeid='123';");  "

So the result set will have details of the trainee id 123. This is how we can make sql connection to fetch/get data from database.

File : SqlConnect.java

import java.sql.*;
public class SqlConnect {
    public static void main(String[] args){
         
          try
          {
           Class.forName("com.mysql.jdbc.Driver");
          }
          catch(ClassNotFoundException cnfe)
          {
           System.out.println("Driver not found"+cnfe);
          }
         
          try
          {
           Connection con= DriverManager.getConnection   ("jdbc:mysql://hostname/DB Name","DBUsername","DBPassword");
           Statement stmt=con.createStatement();
           ResultSet rs=stmt.executeQuery("select Name,placeOfBirth,Batch from trainees_Details where traineeid='123';");
           while(rs.next())
           {
            String nam=rs.getString("Name");
            String place=rs.getString("placeOfBirth");
            String batch=rs.getString("Batch");
            System.out.println(nam+" "+place+""+batch);
           }
           con.close();
          }
          catch(SQLException sqle)
          {
           System.out.println("Data base Error"+sqle);
          }
         
         }
    }

=======================
Publicize Yourself... Free!
http://saalram.com
========================

No comments:

Post a Comment

Saalram.com

Saalram
Publicize yourself ...
http://saalram.com

Free !!!


Place your Ad here - Free!!!
just drop us a mail ... saalram.service@gmail.com

Free !!!