Wednesday, November 18, 2015

Tutorial 1 : Creating a JDBC connection with Swing

Tutorial 1: Step by Step Database Connection with SWING

Step 1: Create a class name MySQLConnector

Step 2: Add the dependencies

import java.sql.*; // for SQL
import javax.swing.*; // for Design

Step 3: // Object for database connection

    Connection conn = null;

Step 4:// Create a class for Connect

    public Connection ConnectDatabase(){
   
        try{
  
           }catch(Exception ex){
            JOptionPane.showMessageDialog(null,ex);
        }
}

Step 5:    Inside try catch block

                 STEP 2: Register JDBC driver
                This will load the MySQL driver, each DB has its own driver
            System.out.println("Register JDBC driver");
            Class.forName("com.mysql.jdbc.Driver");

Step 6-An optional go to the main class and define the variables to be used

   // 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 = "root";
   static final String PASS = "";

//STEP7: Open a connection

      System.out.println("Connecting to database...");
     // conn = DriverManager.getConnection(DB_URL,USER,PASS);
      conn = DriverManager.getConnection("jdbc:mysql://localhost/studenttest","root","");
      return conn;
        }

//Step 8 Catch block

catch(Exception ex){
            JOptionPane.showMessageDialog(null,ex);
            return null;
        }

Step9: Create a Table Staff for login

·         Staff_ID
·         NAME
·         AGE
·         USERNAME
·         PASSWORD

Step 10: Create a New JFRAME Form

·         name it Login_form
·         Add two labels username and password
·         Add a text field
·         Add a Password Field
·         Add a button

Change the variables name

·         username : txt_username
·         password : txt_password
·         button : btn_login

Step11: Put in Panel


Select all the label, field and button
·         right click and enclose in panel
·         Go to properties of panel and select title border

//Step: 12 import the following librarys for Login Form

import java.awt.*;
import java.awt.event.WindowEvent;
import java.sql.*;
import javax.swing.*;

//Step 13: Declare the connection and connector variables for Login Form

    Connection conn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;

 //Step 14 A Closing Event with a Function is created to close the form

    public void close(){
        WindowEvent winClosingEvent = new WindowEvent(this,WindowEvent.WINDOW_CLOSING);
        Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
    }


Step 15: Create a form open event

// event for window opened
    // to do it right click on outside panel then event,-> windowEvent -> windowopened
    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                 
        // TODO add your handling code here:
    }

Step 16: // Step 16: event for window opened

·         // to do it right click on outside panel then event,-> windowEvent -> windowopened
    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                 
        // for the connection the MYSQL
        conn = MySQLConnector.ConnectDatabase();
    }         

Step 17:

·         GO to design
·         Then on button
·         Right Click -> Events -> Mouse -> buttonCLikced

 //when the login button is pressed
    private void btn_loginMouseClicked(java.awt.event.MouseEvent evt) {                                      
        // TODO add your handling code here:
    }

 //Step 18: Write SQL Statements

        String sql= "select * from staff where username=? and password=?";
       

 //Step 19: Try Catch Blocks

        try{
           
        }catch(Exception esql){
           
        }
//////////
catch(Exception esql){

            //step20: print exception

            JOptionPane.showMessageDialog(null, esql);
        }

  // Step 21: Create the Statement object

//The createStatement() method of Connection interface is used to create statement.
 // The object of statement is responsible to execute queries with the database.
            pst =conn.prepareStatement(sql);

 //Step 22: Get the Variable names from entered data

            pst.setString(1,txt_username.getText());
            pst.setString(2,txt_password.getText());


 //Step 23:  // Result set get the result of the SQL query

     //Execute the query : The executeQuery() method of Statement interface
      //is used to execute queries to the database.
       //This method returns the object of ResultSet that can be used to get all the records of a table.
      
            rs = pst.executeQuery();

//Step 24:  Verification of results Retrieved

            if(rs.next()){ // there is some record received only in case of valid username and password
                JOptionPane.showMessageDialog(null,"You Have ENTERED Correct Information");
                close();
            }

//Step 25: else{ // step 25: else portion if the username is not valid

                JOptionPane.showMessageDialog(null,"You Have ENTERED In-Correct Information");
            }

//Step 26: //default close information to dispose

·         Go to design -> main screen -> Properties
·         DeafultCloseOperation from Close to Dispose to see the screen staying there

// Step 27 : Add the sql library


·         Go to library on left pane
·         Select add library
·         then add my-sql jar

//Step 28: Create a new JFrameFrom for showing Staff info


·         rightclick -> New -> JFrameForm and name it as staffinfo

// Step 29 Add this to code to show the staff pane

                Staff_Info s_info = new Staff_Info();
                s_info.setVisible(true);

//Step 30: See Main Function


//Step 31: Right Click Run the file


·         enter correct and incorrect information check the command line

//Step 32: go to staffinfo jframe and add the table from the design pane

·         //then rename by
·         right click on table-> change variable name
·         then enter the name   tbl_staffinfo

//Step 33: Table connector driver rs2xml.jar

www.filesdownload.info/file/69Se66yD/rs2xml.html

//Step 34: Add it to project

go to library -> then properties -> add jar/folder and select rs2xml.jar

//step 35: Go to Staff_info.java


// Step 36: Add the Header files

import java.sql.*;
import javax.swing.*;
import net.proteanit.sql.DbUtils;

 //Step 37:  Define the Connection Statements

    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement pst = null;

 // Step 38: the connection statement

        conn = MySQLConnector.ConnectDatabase();

//Step 39: create a population method

   
    private void Update_table(){
        try{
       
        }catch(Exception ex){
            JOptionPane.showMessageDialog(null, ex);
        }
    }

   //step 40:  select queries

            String sql = "select * from staff";
            pst= conn.prepareStatement(sql);
            rs= pst.executeQuery();

    //Step 41: now use the variable name for the table given when the Jtable was dragged

            tbl_staffinfo.setModel(DbUtils.resultSetToTableModel(rs));

//Step 42: Call the Populate_table()method

        Populate_table();

     

No comments:

Post a Comment