Thursday, 15 January 2015

Database connectivity in java using JDBC-ODBC driver(mini project)


Hi,
This session is about how to connect a Database to a java program using JDBC-ODBC driver.
Firstly you have to download wampserver2.2 for your database.you also need to download the mysqldriver(JAR file).
Install the wampserver and start the sql prompt screen.now you have to create your Database as follows:

step 1.
If it asks for password just hit enter key.Now use the command [create database database_name;].(creates database)
ex: create database student;
step 2. After creating database you have to insert the attributes of your database ex:name,roll_no etc by using the command [use database_name;].
ex: use student;
step 3. Now create table by using command[create table table_name(attribute 1 datatype ,attribute 2 datatype... attribute n datatype);]
ex: create table students(roll integer primary key,name varchar(20));
The database is now ready to use.

1)now  open the netbeans IDE.
2)create new project.
3)now right click on your project name at the upper left cornor of your screen.
4)select ADD JAR/folder.
5)Browse the mysql.jar file and click on add button.

now we have to write the code to connect to the database.
which I have already written below.
Here I have created 3 java files.
1.LG.java
2.DB.java
3.Update.java

For reference visit: https://www.youtube.com/watch?v=26zyOYN4Szk
-----------------------------------------------------------------------------------------------------------------
                                                                                LG.java 

package MyJDBC;

import java.awt.Button;
import java.awt.Checkbox;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Label;
import java.awt.PopupMenu;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 *
 * @author akshay chavan
 */
public class LG extends Frame implements ActionListener{
   static TextField tt1,tt2;
    Label ll1,ll2,ll3;
    static Button bb1;
    static Checkbox cb;
    String id="akshay",pas="1234";
    Font f;
    static Boolean fg=false;
    LG()
    {
        setSize(270,190);
        setTitle("Login");
        setVisible(true);
        setResizable(false);
        setLayout(null);
        setLocation(400,270);
        addWindowListener(new WindowAdapter() {
                        @Override
                        public void windowClosing(WindowEvent we)
                        {
                            if(!fg)
                             dispose();
                       }
              });
        add(pp);
        f=new Font("Georgia",Font.BOLD,14);
        setFont(f);
        tt1=new TextField();
        tt1.setBounds(110,40,150,30);
       
        tt2=new TextField();
        tt2.setBounds(110,80,150,30);
        tt2.setEchoChar('*');
        ll1=new Label("Username:");
        ll1.setBounds(25,40,80,20);
       
        ll2=new Label("Password:");
        ll2.setBounds(25,80,80,20);
        ll3=new Label("");
        ll3.setBounds(30,110,250,20);
        ll3.setForeground(Color.red);
        bb1=new Button("Login");
        bb1.setBounds(120,125,100,50);
        bb1.setForeground(Color.BLUE);
               
        cb=new Checkbox("log in",false);
        cb.setBounds(40,130,60,20);
        cb.setEnabled(false);
        bb1.addActionListener(this);
        add(tt1);
        add(cb);
        add(tt2);
        add(ll3);
        add(ll2);
        add(ll1);
        add(bb1);
    }
   
    public static void main(String[] args) throws Exception{
        // TODO code application logic here
         new LG();
           
    }
   

    @Override
    public  void actionPerformed(ActionEvent e) {
       
        if(e.getSource()==bb1){
           
       
        if(id.equals(tt1.getText()) && pas.equals(tt2.getText())){
        
            tt1.setEnabled(false);
            tt2.setEnabled(false);
            bb1.setEnabled(false);
            cb.setState(true);
            fg=true;
            new DB();
         }
        else{
          
            ll3.setText("Incorrect Username or Password");
            tt1.setText("");
            tt2.setText("");
        }
        }
    }
   
}

------------------------------------------------------------------------------------------------------------------

                                            DB.java 


package MyJDBC;
import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Image;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 *
 * @author akshay chavan
 */
public class DB extends Frame implements ActionListener{
     /* @param args the command line arguments
     */
    Label namel,rolll,titlel;
    TextField namet,rollt;
    Button b1,b2,b3;
    static Button logout;
    static Button b4;
    TextArea ta;
    Image img;
       DB()
       {        
           setSize(500,580);
           setVisible(true);
           setLayout(null);
           setTitle("Students Record");
           setResizable(false);
           Font fn=new Font("Georgia",Font.BOLD,12);
           setFont(fn);
           setForeground(Color.black);
           setBackground(Color.gray);
           setLocation(600,130);
          
           namel=new Label("Name:");
           namel.setBounds(40,450,50,30);
          
           rolll=new Label("Roll NO:");
           rolll.setBounds(190,450,70,30);
          
           namet=new TextField();
           namet.setBounds(90,450,90,30);
          
           rollt=new TextField();
           rollt.setBounds(260,450,90,30);
          
           b1=new Button("ADD record");
           b1.setBounds(40,500,100,50);
          
           b2=new Button("DELETE record");
           b2.setBounds(150,500,100,50);
          
           b3=new Button("DISPLAY record");
           b3.setBounds(260,500,100,50);
          
           b4=new Button("UPDATE record");
           b4.setBounds(370,500,100,50);
          
           ta=new TextArea();
           ta.setBounds(50,80,400,350);
           ta.setBackground(Color.LIGHT_GRAY);
           ta.setFocusable(false);
          
           logout=new Button("Logout");
           logout.setBounds(380,450,90,30);
            
           logout.setForeground(Color.black);
           logout.setBackground(Color.orange);
          
             titlel=new Label("Sr.No              _Roll no_                  _Name_");
             titlel.setBounds(100,50,400,30);
             titlel.setForeground(Color.ORANGE);
            
           add(namel);
           add(rolll);
           add(namet);
           add(rollt);
           add(b1);
           add(b2);
           add(b3);
           add(b4);
           add(logout);
           add(ta);
           add(titlel);
           b1.addActionListener(this);
           b2.addActionListener(this);
           b3.addActionListener(this);
           b4.addActionListener(this);
           logout.addActionListener(this); 
       }
          
       public void display(){
           int i=1;
           try {
               ta.setForeground(Color.BLUE);
             Class.forName("com.mysql.jdbc.Driver");
             Connection con=DriverManager.getConnection("jdbc:mysql://localhost/student?user=root");
             Statement stmt= con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
             ResultSet rs=stmt.executeQuery("select * from students");
              rs.beforeFirst();
        ta.setText("");
        while(rs.next()){
           ta.append("     \t"+i+"\t\t"+rs.getString(1)+"\t\t"+rs.getString(2)+"\n");
                   i++;
                }    
                rs.close();
                        con.close();
            } catch (Exception ex) {
            }
       }
   

    @Override
    public void actionPerformed(ActionEvent e){
      
       int i=1;
        if(e.getSource()==b1)
        {
             try {
             Class.forName("com.mysql.jdbc.Driver");
             Connection con=DriverManager.getConnection("jdbc:mysql://localhost/student?user=root");
             Statement stmt= con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
             stmt.executeUpdate("insert into students values("+(Integer.parseInt(rollt.getText()))+",'"+namet.getText()+"')");
          } catch (Exception ex) {}
            rollt.setText("");
            namet.setText("");
            rollt.setFocusable(true);
        }
       
         if(e.getSource()==b2)
        {
             try {
             Class.forName("com.mysql.jdbc.Driver");
             Connection con=DriverManager.getConnection("jdbc:mysql://localhost/student?user=root");
             Statement stmt= con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                int executeUpdate = stmt.executeUpdate("delete from students where roll="+rollt.getText());
          } catch (Exception ex) {}
            namet.setText(" ");
            rollt.setText(" ");
            rollt.setFocusable(true);
        }
        
           if(e.getSource()==b4)
           {
                    b4.setEnabled(false);
                    logout.setEnabled(false);
                    new Update(namet.getText(),rollt.getText());
                    rollt.setText(" ");
                    namet.setText(" ");
           }
            
            if(e.getSource()==logout)
            {
                       addWindowListener(new WindowAdapter() {
                        @Override
                        public void windowClosing(WindowEvent we)
                        {
                       
                             dispose();
                       }
                        });
                          LG.tt1.setEnabled(true);
                          LG.tt2.setEnabled(true);
                          LG.bb1.setEnabled(true);
                          LG.cb.setState(false);
                               LG.tt2.setText("");
                               LG.fg=false;
                             dispose();                          
            }  
              
           display();
        }                      
 }


---------------------------------------------------------------------------------------------------------------------------------

                                                     Update.java


package MyJDBC;
import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 *
 * @author akshay chavan
 */
public class Update extends Frame implements ActionListener{
    Label lu1,lu2,lu3,lu4;
    TextField tu1,tu2,tu3,tu4;
    String name,roll;
    Button up;
     Update(String name,String roll) {
         setSize(320,120);
         setVisible(true);
         setResizable(false);
         setTitle("Update Record");
         setLayout(null);
         Font fm=new Font("Georgia",Font.BOLD,13);
         setFont(fm);
         setLocation(640,400);
         addWindowListener(new WindowAdapter() {
                        @Override
                        public void windowClosing(WindowEvent we)
                        {
                             DB.b4.setEnabled(true);
                             dispose();
                       }
              });
         this.name=name;
         this.roll=roll;
         tu1=new TextField();
         tu1.setBounds(120,40,100,30);
       
        tu2=new TextField();
        tu2.setBounds(120,70,100,30);
       
       
        lu1=new Label("Name:");
        lu1.setBounds(25,40,80,20);
       
        lu2=new Label("Roll No:");
        lu2.setBounds(25,70,80,20);

         up=new Button("UPDATE");
         up.setBounds(230,40,70,60);
         up.setForeground(Color.MAGENTA);
         add(lu1);
         add(lu2);
         add(tu1);
         add(tu2);
         add(up);
         up.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
           try {
             Class.forName("com.mysql.jdbc.Driver");
             Connection con=DriverManager.getConnection("jdbc:mysql://localhost/student?user=root");
             Statement stmt1= con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
             Statement stmt2= con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
             stmt1.executeUpdate("update students set name='"+tu1.getText()+"' where name='"+name+"'");
             stmt2.executeUpdate("update students set roll="+(Integer.parseInt(tu2.getText()))+" where roll="+roll);
          } catch (Exception ex) {
  
                                 }
            tu1.setText("");
            tu2.setText("");
            tu1.setFocusable(true);
           
            DB.b4.setEnabled(true);
            DB.logout.setEnabled(true);
            dispose();           
    }       
}
output of the program


4 comments:

  1. Sir, i have run your code and there is just one error of variable pp which is used in file LG.java and not declared anywhere. please resolve this error ASAP.
    Thanks :)

    ReplyDelete
  2. U can remove that n run...
    Its working.

    ReplyDelete
  3. Not Happening anything by removing it... Help

    ReplyDelete