Ad

Monday, January 25, 2016

Step By Step Core Java Project using JDBC-ODBC NetBeans IDE & SQL Server Database- by Vikash Chandra Das

Here you can find a small GUI project using JDBC-ODBC NetBeans IDE & Microsoft SQL Server step by step.

1. Open Netbeans



2. Create a New NetBeans Java Application Project.






3. Set your Project Name, Location etc. & Click Finish.


4. Add a new JFrame Form to your Project & rename it to Employee.




5. Design you Form  by adding controls from palette & change control Properties.




6. Change all controls variable name.



7. Create SQL Server Database & Tables.





8. Execute Queries.

create database JDBCTest

use JDBCTest

create table userAccount
(
id int primary key not null,
name varchar(20) not null,
password varchar(20) not null
)

insert into userAccount values(1001, 'Vikash Chandra Das','p@ssw0rd')

select * from userAccount



9. ODBC Settings.
  • Open Control Panel\All Control Panel Items\Administrative Tools
  • Open ODBC Data Sources
  • Add >> Sql Server >> Finish








  • Provide name to use for data source reference - HRM
  • Provide your server name (your system/server name or '.' for local machine)
  • Click Next and set authenticity (Window NT without id & password / SQl Server with id & password)
  • Click Next and select your default database.
  • Click Next and Finish.
  • Click 'Test Data Source' to confirm success connectivity.











  • Click OK >> OK >> OK
10. Writing Codes  to NetBeans GUI Form.


  • Double Click on buttons or Right Click on Button Event >> Actions >> avtionPerformed
  • Add Packages to top of your program.
    • import java.sql.*;
    • import javax.swing.JOptionPane;
11. Submit/Insert Code


private void Click(java.awt.event.MouseEvent evt) {                

        try
        {
            if((txtempid.getText() == null ? "" == null : txtempid.getText().equals("")) ||(txtname.getText() == null ? "" == null : txtname.getText().equals("")) || (txtage.getText() == null ? "" == null : txtage.getText().equals(""))||(txtaddress.getText() == null ? "" == null : txtaddress.getText().equals("")) ||(txtmob.getText() == null ? "" == null : txtmob.getText().equals(""))) 
//Auto generated by Alt+Enter in NetBeans IDE. You may make it short by other Alt+Enter options
            {
                lblMessage.setText("Please fill all details."); //optional
                JOptionPane.showMessageDialog(null, "Please make sure all fields are filled in");
            }
            else
            {
        Connection con = null;
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        con = DriverManager.getConnection("jdbc:odbc:HRM", "sa", "p@ssw0rd");
        PreparedStatement s;
        s= con.prepareStatement("Insert into emp values(?,?,?,?,?)");
        String id = txtempid.getText();
        String name = txtname.getText();
        String age = txtage.getText();
        String add = txtaddress.getText();
        String mob = txtmob.getText();

        s.setString(1, id);
        s.setString(2, name);
        s.setString(3, age);
        s.setString(4, add);
        s.setString(5, mob);

        s.executeUpdate();

        txtempid.setText("");
        txtname.setText("");
        txtage.setText("");
        txtaddress.setText("");
        txtmob.setText("");
        lblMessage.setText("Data Successfully Inserted.");//optional
        JOptionPane.showMessageDialog(null, "Data Successfully Inserted.");
            }
        }
        catch (Exception e)
        {
        lblMessage.setText("Some Error is there!!" +e.toString());//optional
        JOptionPane.showMessageDialog(null, "Error."+e.toString());
        }
    }                      



12. Search Code

private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try
        {
            if(txtSearchId.getText() == null ? "" == null : txtSearchId.getText().equals(""))
            {
                lblMessage.setText("Please fill all details.");
                txtSearchId.setBackground(Color.orange);
                JOptionPane.showMessageDialog(null, "Please Enter Valid Id in searchbox.");
            }
            else
            {
                txtSearchId.setBackground(Color.white);
         Connection con = null;
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         con = DriverManager.getConnection("jdbc:odbc:HRM", "sa", "p@ssw0rd");

         PreparedStatement s;
         String id = txtSearchId.getText();
         s= con.prepareStatement("select empid, name, age, addr, mob from emp where empid = '"+id+"'");
         ResultSet rs = s.executeQuery();
         if (rs.next()==true)
         {
         String empid = rs.getString(1);
         String empname = rs.getString(2);
         String age = rs.getString(3);
         String addre = rs.getString(4);
         String phon = rs.getString(5);

        txtempid.setText(empid);
        txtname.setText(empname);
        txtage.setText(age);
        txtaddress.setText(addre);
        txtmob.setText(phon);
        lblMessage.setText("Data Searched.");
          }
        else
         {
              JOptionPane.showMessageDialog(null, "No Records found.");
         }

            }
        }
        catch (Exception e)
        {
        lblMessage.setText("Some Error is there!!" +e);
        }
    }                                

13. Update Code

private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
        try
        {
            if((txtSearchId.getText() == null ? "" == null : txtSearchId.getText().equals("")))
            {
                lblMessage.setText("Please fill Id in Search Id box.");
                JOptionPane.showMessageDialog(null, "Please make sure all fields are filled in for this operation.");
            }
            else
            {
         Connection con = null;
         String ids = txtSearchId.getText();
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         con = DriverManager.getConnection("jdbc:odbc:HRM", "sa", "p@ssw0rd");

         PreparedStatement s;

         s= con.prepareStatement("Update emp set name=(?), age=(?),addr =(?),mob=(?) where empid = '"+ids+"'");


        //String id = txtempid.getText();
        String name = txtname.getText();
        String age = txtage.getText();
        String add = txtaddress.getText();
        String mob = txtmob.getText();
        s.setString(1, name);
        s.setString(2, age);
        s.setString(3, add);
        s.setString(4, mob);

        s.executeUpdate();

        txtempid.setText("");
        txtname.setText("");
        txtage.setText("");
        txtaddress.setText("");
        txtmob.setText("");
        lblMessage.setText("Data Successfully Updated.");
            }
        }
        catch (Exception e)
        {
        lblMessage.setText("Some Error is there!!" +e);
        }
    }


14. Delete Code

private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                         
         try
        {
            if(txtDeleteId.getText() == null ? "" == null : txtDeleteId.getText().equals(""))
            {
                lblMessage.setText("Please fill all details.");
                txtDeleteId.setBackground(Color.orange);
                JOptionPane.showMessageDialog(null, "Please Enter Valid Id in deletebox.");
            }
            else
            {
                txtDeleteId.setBackground(Color.white);
         Connection con = null;
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         con = DriverManager.getConnection("jdbc:odbc:HRM", "sa", "p@ssw0rd");

         PreparedStatement s;
         String id = txtDeleteId.getText();
         s= con.prepareStatement("Delete emp where empid = '"+id+"'");
         int rs = s.executeUpdate();
     
      
        JOptionPane.showMessageDialog(null, "Data Deleted.");
        txtDeleteId.setText("");               
            }
           
        }
        catch (Exception e)
        {
        JOptionPane.showMessageDialog(null, "No Records found.");
        lblMessage.setText("Some Error is there!!" +e);
        }
    }                    

15. Display SQL Tables all record Code 

Create a Java Class/File and write the following Code

import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableFromSqlServer extends JFrame {

    public TableFromSqlServer() {
        ArrayList colNames = new ArrayList();
        ArrayList data = new ArrayList();

        try {
            Connection con = null;
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con = DriverManager.getConnection("jdbc:odbc:HRM", "sa", "p@ssw0rd");
            PreparedStatement s;
            s = con.prepareStatement("select * from emp");
            ResultSet rs = s.executeQuery();
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();

            for (int i = 1; i <= columns; i++) {
                colNames.add(md.getColumnName(i));
            }

            while (rs.next()) {
                ArrayList row = new ArrayList(columns);

                for (int i = 1; i <= columns; i++) {
                    row.add(rs.getObject(i));
                }

                data.add(row);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        Vector columnNamesVector = new Vector();
        Vector dataVector = new Vector();

        for (int i = 0; i < data.size(); i++) {
            ArrayList subArray = (ArrayList) data.get(i);
            Vector subVector = new Vector();
            for (int j = 0; j < subArray.size(); j++) {
                subVector.add(subArray.get(j));
            }
            dataVector.add(subVector);
        }

        for (int i = 0; i < colNames.size(); i++) {
            columnNamesVector.add(colNames.get(i));
        }
   
        JTable table = new JTable(dataVector, columnNamesVector) {
            public Class getColumnClass(int column) {
                for (int row = 0; row < getRowCount(); row++) {
                    Object o = getValueAt(row, column);

                    if (o != null) {
                        return o.getClass();
                    }
                }

                return Object.class;
            }
        };

        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);

        JPanel buttonPanel = new JPanel();
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {
        TableFromSqlServer frame = new TableFromSqlServer();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

16. Changing Java JDK Version in NetBeans

If you find any error due to new or old versions of java you can easily change by following steps.










Vikash Chandra Das
Rourkela
Odisha


No comments:

Post a Comment