Programs based on JDBC.

a.Demonstration of JDBC component. Connecting to database and retrieving data from database

CODE:

package swing_practicals;

import java.sql.*;

public class jdbcdemo {

    Connection conn;

    Statement st;

    ResultSet rs;

    public jdbcdemo() {

    try

    {

        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

    }

    catch(ClassNotFoundException e){

            System.out.println(e);

    }

    try{

        conn = DriverManager.getConnection("jdbc:sqlserver://localhost:5000;databaseName=gv","sa","gv30");

        st = conn.createStatement();

        rs = st.executeQuery("select * from student");

        System.out.print("Roll No.\tName\tAddress\n");

            while (rs.next())

            {

                System.out.println(rs.getInt(1)+"\t\t"+rs.getString(2)+"\t"+rs.getString(3));

                

            }

    }

    catch(SQLException e){

        System.out.println(e);}

    }

    public static void main(String[] args){

        new jdbcdemo();

    }  

}

output:

Programs based on JDBC.


b. Program to illustrate the use of 

executeUpdate() method.

CODE:

package swing_practicals;

import java.sql.*;

import java.util.Scanner;

public class jdbctest2 {

    Connection conn;

    Statement st;

    PreparedStatement ps;

    ResultSet rs;

    ResultSetMetaData rsmd;

    int ch;

    public jdbctest2() {

        try

        {

            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        }

        catch(ClassNotFoundException e){

                System.out.println(e);

        }

        try{

conn=DriverManager.getConnection("jdbc:sqlserver://localhost:5000;databaseName=gv","sa","gv30");

            st = conn.createStatement();

            Scanner sc = new Scanner(System.in);

            do{

                System.out.print("Enter emp id:");

                int id = sc.nextInt();

                System.out.print("Enter emp name:");

                String name = sc.next();

                System.out.print("Enter emp salary:");

                int sal = sc.nextInt();

                System.out.print("Enter emp location:");

                String loc = sc.next();

                String str = "insert into emp values(?,?,?,?)";

                ps = conn.prepareStatement(str);

                ps.setInt(1, id);

                ps.setString(2, name);

                ps.setInt(3, sal);

                ps.setString(4, loc);

                ps.executeUpdate();

                System.out.print("Do you want to continue(1/0)");

                ch = sc.nextInt();

            }while(ch==1);

            rs = st.executeQuery("select * from emp");

            rsmd = rs.getMetaData();

            int c = rsmd.getColumnCount();

            for(int i=1;i<=c;i++){

                System.out.print(rsmd.getColumnName(i)+"\t");

            }

            System.out.println();

            while(rs.next()){

System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getInt(3)+"\t"+rs.getString(4));

            }

        }

        catch(SQLException ae){

            System.out.println(ae);

        }

    }

    public static void main(String[] args){

        new jdbctest2();       

    }

}

 

OUTPUT:

Program to illustrate the use of   executeUpdate() method.

c. Create emp table  with emp_id, Name, salary and Location in database using java code, perform insert, delete and select query on the table.

CODE:

package swing_practicals;

import java.sql.*;

public class jdbctest {

    Connection conn;

    Statement st;

    ResultSet rs;

    ResultSetMetaData rsmd;

    public jdbctest() {

        try

        {

            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        }

        catch(ClassNotFoundException e){

                System.out.println(e);

        }

        try{

            conn = DriverManager.getConnection("jdbc:sqlserver://localhost:5000;databaseName=gv","sa","gv30");

            st = conn.createStatement();

            String str = "create table emp(emp_id int,name varchar(20),salary int,location varchar(20))";

            int r = st.executeUpdate(str);

            //String str1 = "insert into emp values(1,'Kiran',60000,'Mumbai')";

            //int r = st.executeUpdate(str1);

            //String str2 = "delete emp where emp_id=1";

            //int r = st.executeUpdate(str2);

           // System.out.println(r+" executed successfully.");

            rs = st.executeQuery("select * from emp");

            rsmd = rs.getMetaData();

            int c = rsmd.getColumnCount();

            for(int i=1;i<=c;i++){

                System.out.print(rsmd.getColumnName(i)+"\t");  

            }

            System.out.println();

            while(rs.next()){

     System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getInt(3)+"\t"+rs.getString(4));

            }

        }

        catch(SQLException ea){

            System.out.println(ea);

        }

    }

    public static void main(String args[]){                                  

        new jdbctest();                                    

    }

    

}

OUTPUT:

Programs based on JDBC.

d. Develop swing application FORM , take input from user’s  Name, Date of Birth, Address and Telephone number . Create command button “ADD”  on click the user data is saved in database. Also create button “SHOW ALL”. On click it will show all entries of database.

CODE:

 

package swing_practicals;

import java.sql.*;

public class C extends javax.swing.JFrame {

    Connection con;

    Statement st;

    PreparedStatement pst;

    ResultSet rs;

    ResultSetMetaData rsm;

    public C() {

        try

        {

            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            con= DriverManager.getConnection("jdbc:sqlserver://localhost:5000;databaseName=gv","sa","gv30");

        }

        catch(Exception e){

                System.out.println(e);

        }   

        initComponents();

    }

    @SuppressWarnings("unchecked")

    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          

    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();

        jLabel2 = new javax.swing.JLabel();

        jLabel3 = new javax.swing.JLabel();

        jLabel4 = new javax.swing.JLabel();

        name = new javax.swing.JTextField();

        dob = new javax.swing.JTextField();

        add = new javax.swing.JTextField();

        tel = new javax.swing.JTextField();

        addbtn = new javax.swing.JButton();

        show = new javax.swing.JButton();

        jScrollPane1 = new javax.swing.JScrollPane();

        txtarea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N

        jLabel1.setText("Enter your Name :");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N

        jLabel2.setText("DOB :");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N

        jLabel3.setText("Adress :");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N

        jLabel4.setText("Tel. No. :");

       name.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                nameActionPerformed(evt);

            }

        });

        dob.setToolTipText("");

        dob.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                dobActionPerformed(evt);

            }

        });

        addbtn.setBackground(new java.awt.Color(51, 255, 255));

        addbtn.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N

        addbtn.setText("ADD");

        addbtn.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                addbtnActionPerformed(evt);

            }

        });

        show.setBackground(new java.awt.Color(153, 0, 153));

        show.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N

        show.setText("Show All");

        show.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                showActionPerformed(evt);

            }

        });

        txtarea.setColumns(20);

        txtarea.setRows(5);

        jScrollPane1.setViewportView(txtarea);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

        getContentPane().setLayout(layout);

        layout.setHorizontalGroup(

            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addGroup(layout.createSequentialGroup()

                .addGap(22, 22, 22)

                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)

                    .addGroup(layout.createSequentialGroup()

                        .addComponent(addbtn, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)

                        .addGap(98, 98, 98)

                        .addComponent(show, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE))

                    .addGroup(layout.createSequentialGroup()

         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)

                                .addComponent(jLabel1)

                                .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)

                                .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING))

                            .addComponent(jLabel4))

                        .addGap(38, 38, 38)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)

                            .addComponent(name)

                            .addComponent(dob, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)

                            .addComponent(add)

                            .addComponent(tel))))

                .addContainerGap(322, Short.MAX_VALUE))

            .addGroup(layout.createSequentialGroup()

                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 556, javax.swing.GroupLayout.PREFERRED_SIZE)

                .addGap(0, 106, Short.MAX_VALUE))

        );

        layout.setVerticalGroup(

            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addGroup(layout.createSequentialGroup()

                .addGap(24, 24, 24)

                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)

                    .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)

                    .addComponent(dob, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                    .addComponent(jLabel3)

                    .addComponent(add, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                    .addComponent(jLabel4)

                    .addComponent(tel, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))

                .addGap(39, 39, 39)

                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                    .addComponent(addbtn)

                    .addComponent(show, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))

                .addGap(18, 18, 18)

                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 310, Short.MAX_VALUE))

        );

        pack();

    }// </editor-fold>                        

    private void nameActionPerformed(java.awt.event.ActionEvent evt) {                                     

        

    }                                    

    private void showActionPerformed(java.awt.event.ActionEvent evt) {                                     

        name.setText("");

        dob.setText("");

        add.setText("");

        tel.setText("");

        try{

            String query= "select * from friends";

            st = con.createStatement();

            rs = st.executeQuery(query);

            rsm = rs.getMetaData();

            int cols = rsm.getColumnCount();

            for(int i=1;i<=cols;i++){

                txtarea.append(rsm.getCatalogName(i)+"\t");  

            }

            txtarea.append("\n");

            while(rs.next()){

                String name = rs.getString(1);

                String dob = rs.getString(2);

                String add = rs.getString(3);

                String no = rs.getString(4);

                txtarea.append(name+"\t"+dob+"\t"+add+"\t"+no+"\n");

            }

            

        }

        catch(Exception e){

            e.printStackTrace();

        }

    }                                    

    private void addbtnActionPerformed(java.awt.event.ActionEvent evt) {                                       

        String n = name.getText();

        String dob1 = dob.getText();

        String addr = add.getText();

        String no = tel.getText();

        try{

            String query = "insert into friends values(?,?,?,?)";

            pst = con.prepareStatement(query);

            pst.setString(1, n);

            pst.setString(2, dob1);

            pst.setString(3, addr);

            pst.setString(4, no);

            int i = pst.executeUpdate();

            pst.close();

        }

        catch(Exception e){

            e.printStackTrace();

        }

        name.setText("");

        dob.setText("");

        add.setText("");

        tel.setText("");

        

    }                                      

    private void dobActionPerformed(java.awt.event.ActionEvent evt) {                                    

        

    }                                   

    public static void main(String args[]) {

        try {

            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {

                if ("Nimbus".equals(info.getName())) {

                    javax.swing.UIManager.setLookAndFeel(info.getClassName());

                    break;

                }

            }

        } catch (ClassNotFoundException ex) {

            java.util.logging.Logger.getLogger(C.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (InstantiationException ex) {

            java.util.logging.Logger.getLogger(C.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (IllegalAccessException ex) {

            java.util.logging.Logger.getLogger(C.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (javax.swing.UnsupportedLookAndFeelException ex) {

            java.util.logging.Logger.getLogger(C.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

        }

                java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {

                new C().setVisible(true);

            }

        });

    }

    // Variables declaration - do not modify                     

    private javax.swing.JTextField add;

    private javax.swing.JButton addbtn;

    private javax.swing.JTextField dob;

    private javax.swing.JLabel jLabel1;

    private javax.swing.JLabel jLabel2;

    private javax.swing.JLabel jLabel3;

    private javax.swing.JLabel jLabel4;

    private javax.swing.JScrollPane jScrollPane1;

    private javax.swing.JTextField name;

    private javax.swing.JButton show;

    private javax.swing.JTextField tel;

    private javax.swing.JTextArea txtarea;

    // End of variables declaration                   

}

OUTPUT:

Develop swing application FORM , take input from user’s  Name, Date of Birth, Address and Telephone number . Create command button “ADD”  on click the user data is saved in database. Also create button “SHOW ALL”. On click it will show all entries of database.

















Post a Comment

0 Comments