Saturday, October 26, 2013

JDBC -JAVA DATABASE CONNECTIVITY USING MY SQL

Creating JDBC Application:

There are following six steps involved in building a JDBC application:
  • Import the packages . Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
  • Register the JDBC driver . Requires that you initialize a driver so you can open a communications channel with the database.
  • Open a connection . Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.
  • Execute a query . Requires using an object of type Statement for building and submitting an SQL statement to the database.
  • Extract data from result set . Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set.
  • Clean up the environment . Requires explicitly closing all database resources versus relying on the JVM's garbage collection.

Sample Code:

This sample example can serve as a template when you need to create your own JDBC application in the future.
This sample code has been written based on the environment and database setup done in previous chapter.
Copy and past following example in FirstExample.java, compile and run as follows:
//STEP 1. Import required packages
import java.sql.*;

public class FirstExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/EMP";

   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";
   
   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);

      //STEP 5: Extract data from result set
      while(rs.next()){
         //Retrieve by column name
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");

         //Display values
         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      }
      //STEP 6: Clean-up environment
      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      }// nothing we can do
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end FirstExample
 
Now let us compile above example as follows:
C:\>javac FirstExample.java
C:\>
When you run FirstExample, it produces following result:
C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>

Wednesday, October 16, 2013

ADDING THE SUPPORTING FILES FOR JDBC CONNECTION TO THE PROJECT-IN NETBEANS ONLY


First, Create new Project named anything you want, for example Javasql by click File->New Project.
newProject
newProject
then you’ll be on this frame
javaapps
javaapps
then click next,  then give Project Name and set Project Localtion
nameProject
nameProject
then finish.
Second, you must have JDBC MySQL Driver before you can start to connect your Java program to database. But since we use Netbeans , this has been done. Just simply add the library to your project library. Right click in Library on the Project you use. addLibrary
Then choose MySQL JDBC Driver
addLib
Then Click Add Libary.
So now we can connect to MySQL database. 

THIS SHOULD BE DONE BEFORE EXECUTING THE JDBC CODINGS.NOW THE CONNECTION IS ESTABLISHED TO THE MY SQL DATABASE

Tuesday, October 15, 2013

USEFUL SQL QUERIES AND INFORMATIONS

SQL DATA TYPES:
`````````````````````````
1     1  Number ->Size 38 digit
2      Character ->size upto 2000 bytes
3      Varchar2 -> 4000 bytes
4      Date ->9 bytes
5      Long data type ->2 GB
6      Raw ->store binary data
7      Long Raw ->2 GB
8      Lob ->Blob(binary lob),clob(character lob)
SSQL OPERATORS:
````````````````````````````
1)      Operator -> +,-,*,/   
Example ->select sal+100 from emp;
2)      Comparison operator  ->  =,>,<=,>=,||,(<>,!=    <-not equal to )
Example ->select * from emp where sal > 3000;
3)      Logical operator -> and, or, not
Example -> select * from emp where ename=’smith’ and sal=800;
4)      Comparison operator ->between and, not between ,in , not in, like ,in null
Select * from emp where sal between 2000 and 3000 ;
Select * from emp where deptno in (10,20);

Select ename from emp where sal>=1000 and job like ‘%m’;

DATA DEFINITION LANGUAGE (DDL):
``````````````````````````````````````````````````````````
Create:

SQL> create table bank(accno number(3),branch varchar(20),cname varchar(20));
Table created.

SQL> desc bank;
 Name                                                  Null?    Type
 ------------------------------------------- -------- ------------------------------------
 ACCNO                                                          NUMBER(3)
 BRANCH                                                        VARCHAR2(20)
 CNAME                                                          VARCHAR2(20)

Alter:
SQL> desc bank;
 Name                                                  Null?    Type
 ------------------------------------------- -------- ------------------------------------
 ACCNO                                                          NUMBER(3)
 BRANCH                                                        VARCHAR2(20)
 CNAME                                                          VARCHAR2(20)

SQL> alter table bank add(balance number(4));

Table altered.

SQL> desc bank;
 Name                                                  Null?    Type
 ------------------------------------------- -------- ------------------------------------
 ACCNO                                                             NUMBER(3)
 BRANCH                                                           VARCHAR2(20)
 CNAME                                                             VARCHAR2(20)
 BALANCE                                                         NUMBER(4)

Truncate:

SQL> truncate table bank;
Table truncated.

Delete:
SQL> drop table bank;
Table dropped.

DATA  MANIPULATION  LANGUAGE (DML):
``````````````````````````````````````````````````````````````````
Insert:

SQL> insert into bank (accno, cname, branch) values (2444,'dhana','salem');
1 row created.

SQL> insert into bank values(444,'hari','chennai');
1 row created.

SQL> insert into bank values(&accno,'&cname','&branch');
Enter value for accno: 100
Enter value for cname: arun
Enter value for branch: erode
old    1: insert into bank values(&accno,'&cname','&branch');
new  1: insert into bank values(100,'arun','erode')

select:

SQL> select*from bank;

 ACCNO        CNAME                 BRANCH
 ---------          --------------------    --------------------
  2444              dhana                     salem
  444                hari                        Chennai
  100                arun                        erode

SQL>select  cname,branch where accno=444;

ACCNO        CNAME                 BRANCH
 ---------          --------------------    --------------------
    444                hari                        Chennai

SQL>select branch where accno=100 and branch=Chennai;
ACCNO        CNAME                 BRANCH
---------          --------------------    --------------------
100                 arun                        erode






Update:

SQL>update bank set accno=244 where accno=2444;
1 row updated;

SQL>select*from bank;

 ACCNO        CNAME                 BRANCH
 ---------          --------------------    --------------------
  244               dhana                       salem
  444                hari                         Chennai
  100                arun                        erode

Delete:

SQL>delete  from bank where cname=’dhana’;

SQL>select*from bank;

 ACCNO        CNAME                 BRANCH
 ---------          --------------------    --------------------
  444                hari                         Chennai
  100                arun                        erode





Thursday, October 10, 2013

JAVA DATABASE CONNECTIVITY(JDBC)

Now let we see about how to connect java with database:

A java database connectivity is an application which will behave as an interface between the java program and the database.

Database driver are 2 types:-
1)thick driver(java->driver->odbc->database)
2)thin driver(java->driver->database)

java have 4 driver:-
1)type 1 driver acts as a bridge between jdbc and other database connectivity mechanisms such as odbc.

java prg->jdbc api->jdbc driver->odbc driver->native api ->db

2)type 2 driver converts jdbc call into database vendor specific native call in a client machine.

java prg->jdbc api->jdbc driver->native api ->db

3)type 3 driver translates jdbc calls into database server independent and middleware server specific net protocol calls which are then translated into database server specific calls by the middleware server.

java prg->jdbc api->middleware server ->db

4)type 4 driver is a pure java driver which implements the database protocol to interact directly with a database.

java prg->jdbc api->jdbc driver->db

To interact with database the necessary steps are :-
----------------------------------------------------------------
1)Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
load the driver class in the memory

2)Connection con=DriverManager.getConnection("jdbc:odbc:san","scott","tiger");
get connection from DriverManager

3)Statement st=con.createStatement();
get a statement from connection

4)ResultSet rs=st.executeQuery("select * from emp");
ResultSet interface refer memory Buffer
using statement executeQuery

Sql package has 2 classes and 8 interfaces:-
--------------------------------------------------------
classes :-DriverManager,Types
interface :-Driver,Connection,Statement,PreparedStatement,CallableStatement,
ResultSet,ResultSetMetaData,DatabaseMetaData

there are 3 methods in statement interface
1)executeQuery()->select
2)executeUpdate()->update(return 0,1)
3)execute()->insert,delete,create,drop(return true,false)

java datatype:-String,int,double,JavaObject
Jdbc datatype:-varchar,char,number,number(7,2),clob,blob

to obtain data:-
getInt(),getString(),getDouble,getFloat(),getByte(),getShort(),getBoolean(),
getLong(),getObject(),getChar()

Statement ->
It can handle one statement at one time.

PreparedStatement->
It can handle multiple sql queries.
It also used for putting the values for the sql queries at the runtime.
It is faster than the statement

Callable Statement->
It is used to call stored functions and procedures of database.

Type 4 driver:-
-------------------------

import java.sql.*;
class SqlTest
{
public static void main(String arg[])throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
jdbc->protocol
oracle->database
thin->type4
localhost->local machine
1521->port no
orcl->service id of oracle
scott->username
tiger->password
CallableStatement st=con.prepareCall("{call addition(?,?,?)}");
st.setInt(1,10);
st.setInt(2,20);
st.registerOutParameter(3,Types.INTEGER);
st.execute();
int n=st.getInt(3);
System.out.println(n);
}
}
-----------------



ResultSetMetaData:-

ResultSetMetaData md=rs.getMetaData();
System.out.println(md.getColumnCount());
System.out.println(md.getColumnName());

DatabaseMetaData:-

DatabaseMetaData md=rs.getMetaData();
System.out.println(md.getDriverVersion());
System.out.println(md.getDriverName());

JAVA PROGRAM TO CREATE MENU BAR

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class access extends JFrame 
{
MenuBar mb;          //TO CREATE MENU
Menu m1,m2,m3;
    MenuItem mi1,mi2,mi3,mi4,mi5;          // TO CREATE PARTICULAR MENU ITEM IN MENU
access()
{
Container c=getContentPane();
                   JLabel jl=new JLabel("Menu Bar Example");
 jl.setBounds(60,10,770,30);
 jl.setFont(new Font("Times New Roman", Font.BOLD,30));
 jl.setBackground(Color.black);
 jl.setForeground(Color.blue);
 c.add(jl);
 JLabel jl2=new JLabel(new ImageIcon("images/c1.jpg"));
 jl2.setBounds(550,100,350,170);
 jl2.setBackground(Color.black);
 c.add(jl2);
JLabel jl4=new JLabel(new ImageIcon("images/c1.jpg"));
 jl4.setBounds(150,100,350,170);
 jl4.setBackground(Color.black);
 c.add(jl4);
JLabel jlab=new JLabel(new ImageIcon("images/welcome1.gif"));
 jlab.setBounds(0,0,800,600);
 jlab.setLayout(null); 
 c.add(jlab);

        
    mb=new MenuBar();
        m1=new Menu("FILE");                       //DEFINING MENU
        m2=new Menu("ADMIN");
        m3=new Menu("USER");
mi1=new MenuItem("Click This"); //defining menu item under file menu
        mi2=new MenuItem("REGISTER");     //defining menu item under file menu
        mi3=new MenuItem("ADMIN LOGIN");
   mi4=new MenuItem("USER LOGIN");
m1.add(mi1);
        m1.add(mi2);
        m2.add(mi3);
m3.add(mi4);
                mb.add(m1);
        mb.add(m2);
        mb.add(m3);
        setMenuBar(mb);
        
           setSize(1024,768);
           setVisible(true);
           setTitle("Menu Bar Example");
                   
}
       public static void main(String ar[])
       {
           access ac=new access();
       }
}

OUTPUT:
````````````


Program for password Field

Program:
~~~~~~
import javax.swing.*;
import java.awt.*;
class jpf extends JFrame
{
  Container con;
  JLabel l1,l2,l3;
JTextField t1;
                  JPasswordField p1;  //Class to create Password Field
                 JButton b1,b2;
        jpf()
{
con=getContentPane();
                  con.setLayout(null);
                    l1=new JLabel("Login Page");
    l2=new JLabel("User Name");
   t1=new JTextField();
      l3=new JLabel("Password");
  p1=new JPasswordField();
   b1=new JButton("Submit");
                     b2=new JButton("reset");
                 l1.setBounds(150,50,90,30);
                 l2.setBounds(90,120,90,30);
                 t1.setBounds(180,120,90,30);
                 l3.setBounds(90,180,90,30);
                 p1.setBounds(180,180,90,30);
                 b1.setBounds(90,220,90,30);
                 b2.setBounds(180,220,90,30);
               
                      con.add(l1);
                      con.add(l2);
                      con.add(t1);
                      con.add(l3);
                      con.add(p1);
                      con.add(b1);
                      con.add(b2);
}


   public static void main(String args[]) throws Exception
{
jpf obj=new jpf();
     obj.setVisible(true);
    obj.setSize(400,400);
    obj.setTitle("this is my Frame");

}
}

OUTPUT:
~~~~~~~~


Animated Social Gadget - Blogger And Wordpress Tips