Generating JTable from database table

package process;
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
/**
 * This class create JTable from Database table.
 * User program needs to specify database connection and corresponding atable name.
 * @author Hemraj
 */
public class TableToJTable{
    //private String table;
    private Connection con;
    public TableToJTable(Connection con){
        this.con=con;
    }
    /**
     * This method return JTable object created from Database table having same data asn structure
     * as in original table into database.
     * @param table Name of the database table to be coverted to JTable
     * @return JTable object that consist of data and structure of Database table
     * @throws java.lang.Exception Original object is deferent, e.i either SQLException or NullPointerException
     */
    public JTable getTable(String table)throws Exception{
        JTable t1=new JTable();
        DefaultTableModel dm=new DefaultTableModel();
        Statement st=con.createStatement();   
        ResultSet rs=st.executeQuery("select * from "+table);
        ResultSetMetaData rsmd=rs.getMetaData();
        //Coding to get columns-
        int cols=rsmd.getColumnCount();
        String c[]=new String[cols];
        for(int i=0;i<cols;i++){
            c[i]=rsmd.getColumnName(i+1);
            dm.addColumn(c[i]);
        }
        //get data from rows
        Object row[]=new Object[cols];
        while(rs.next()){
             for(int i=0;i<cols;i++){
                    row[i]=rs.getString(i+1);
                }
            dm.addRow(row);
        }
        t1.setModel(dm);
        con.close();
        return t1;
    }
    /**
     * This method return JTable object created from Database table having selected data and structure
     * as in original table into database.
     * @param table Name of the database table to be coverted to JTable
     * @param query Select query to specify selected columns and data to extracted from database table
     * @return JTable object that consist of selected data and structure of Database table
     * @throws java.lang.Exception Original object is deferent, e.i either SQLException or NullPointerException
     */
    public JTable getTable(String table,String query)throws Exception{
        JTable t1=new JTable();
        DefaultTableModel dm=new DefaultTableModel();
        Statement st=con.createStatement();
        ResultSet rs=st.executeQuery(query);
        ResultSetMetaData rsmd=rs.getMetaData();
        //Coding to get columns-
        int cols=rsmd.getColumnCount();
        String c[]=new String[cols];
        for(int i=0;i<cols;i++){
            c[i]=rsmd.getColumnName(i+1);
            dm.addColumn(c[i]);
        }


        //get data from rows
        Object row[]=new Object[cols];
        while(rs.next()){
             for(int i=0;i<cols;i++){
                    row[i]=rs.getString(i+1);
                }
            dm.addRow(row);
        }
        t1.setModel(dm);
        con.close();
        return t1;
    }


    public static void main(String ar[])throws Exception{
        JFrame f=new JFrame("Title");
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
        process.TableToJTable obj = new process.TableToJTable(con);
        JScrollPane sp=new JScrollPane(obj.getTable("user"));
        f.add(sp);
        f.setBounds(200,200,400,300);
        f.setVisible(true);       
    }
}





Handling Transaction JDBC


Transactions 

In various application we may group the series of statements in such a way that either all of them execute successfully or all to be failed. For example if we want to execute five SQL queries at a time, which are related to each other, like
ü   Search the particular data
ü    Again search for next from second row
ü     add the data retrieved
ü     Insert into third row
ü     Update the row
To do this in the single steps, we need to do the transaction in the given ordered. When multiple statements are executed in a single transaction, all operations can be committed (made permanent in database) or rollback (that is changes to the database are undone).
When a new connection object is created, it is set to commit every time transaction automatically .so we can not rollback, to solve this problem we use the transaction scheme.
There are the following methods of connection interface which are used for transactions.
 boolean  getAutoCommit() Retrieves the current auto-commit mode for this Connection object.
 void commit() Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object.
 void  rollback(Savepoint savepoint) Undoes all changes made after the given Savepoint object was set.
Program
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /**  @author Hemraj   * hemraj_cse2003@yahoo.com  * Program to demonstrate Transaction in JDBC  */ public class JDBCTransaction {     public static void main(String[] args)         throws  ClassNotFoundException{         Connection dbcon=null;             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");           //Define the Datasource for the Driver             String sourceURL="jdbc:odbc:hemraj_db";           //Create the connection through drivermanager             try{             dbcon=DriverManager.getConnection(sourceURL);                 System.out.println("Connection is : \n"+dbcon);           //Set the connection not autocommite             dbcon.setAutoCommit(false);             Statement stmt=dbcon.createStatement();           //String insert="INSERT INTO INFO VALUES('HEM1','RAJ1',8973499)";             System.out.println("Inserted : "+stmt.executeUpdate("INSERT INTO INFO " +                 "VALUES('HEM1','RAJ1',8973499)"));             System.out.println("Inserted : "+stmt.executeUpdate("INSERT INTO INFO " +         "VALUES('HEM2','RAJ2',000499)"));             stmt.executeUpdate("UPDATE TABLE INFO " +                 "SET name='HEMRAJ1' WHERE name=HEM1");           //set The chenges permanent             dbcon.commit();             System.out.println("Transaction Completed");             dbcon.close();             }catch(SQLException e){                 System.out.println("Error,Doing Rollback");                try{                 dbcon.rollback();                 dbcon.close();              }catch( SQLException er){                  System.out.println("Error In rollback");                  }           }     } }

Servlet configuration

Inside servlet container, the object of  javax.servlet.ServletConfig is used to represents the servlet configurations. The configuration information conatains the servlet ‘s initialization parameters, the name of the servlet and servlet contaxt which gives the information about container. The servletinitialization parameter and the servlet name can be spacified in the deployment descriptor (web.xml).

For example
<web-app>
    <servlet>
        <servlet-name>s1</servlet-name>
        <servlet-class>FirstServlet</servlet-class>
        <init-param>
            <param-name>p1</param-name>
            <param-value>bye user</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>s1</servlet-name>    
        <url-pattern>/s1</url-pattern>
    </servlet-mapping>
</web-app>


Following example will retrieves parameter from init-param tag of the servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet{
    public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException{
        res.setContentType("text/html");
        PrintWriter pw=res.getWriter();
        ServletConfig config=getServletConfig();
        String s=config.getInitParameter("p1");
        pw.write(s);
    }
}

Thread synchronization

TestSynchronized.java

// Program to Test Synchronized class MyClass { void myMethod() { System.out.println("Callin method from MyClass "); } } class CommonClass { synchronized public void print(String msg) { System.out.println("Hi"); try { Thread.sleep(1000); } catch(Exception e) { } System.out.println(msg); } } class Syn1 extends Thread { CommonClass cc = null; public void run() { cc.print("From Syn1"); } } class Syn2 extends Thread { CommonClass cc2 = null; public void run() { cc2.print("From Syn2"); } } class TestSynchronized { public static void main(String ar[]) { //creating the object of Synchronized method`s class CommonClass c = new CommonClass(); // Creating the object of extended Thread class Syn1 s1 = new Syn1(); Syn2 s2 = new Syn2(); // assigning the CommonClass type reference to Syn1 and Syn3 Class s1.cc = c; s2.cc2 = c; //starting the thread s1.start(); s2.start(); MyClass mc = new MyClass(); mc.myMethod(); System.out.println("Main Finished"); } }

TestSynchronized1.java

// Program to Test Synchronized class CommonClass { synchronized public void print(String msg) { System.out.println("Hi"); try { Thread.sleep(1000); } catch(Exception e) { } System.out.println(msg); } } class Syn1 extends Thread { CommonClass cc = null; public void run() { cc.print("From Syn1"); } } class Syn2 extends Thread { CommonClass cc2 = null; public void run() { cc2.print("From Syn2"); } } class TestSynchronized1 { public static void main(String ar[]) { //creating the object of Synchronized method`s class CommonClass c = new CommonClass(); // Creating the object of extended Thread class Syn1 s1 = new Syn1(); Syn2 s2 = new Syn2(); // assigning the CommonClass type reference to Syn1 and Syn3 Class s1.cc = c; s2.cc2 = c; //starting the thread s1.start(); s2.start(); // creating another object Syn1 ss1 = new Syn1(); Syn2 ss2 = new Syn2(); ss1.cc = c; ss2.cc2 = c; ss1.start(); ss2.start(); System.out.println("Main Finished"); } }

Find and count files of specified name or extension

import java.io.*;
class CountFileFolder
{
    static String searchFile=".mp3";
    static int count=0;
    public static void main(String ar[])throws IOException
    {
        long s=System.currentTimeMillis();
        search("F:/");
        long e=System.currentTimeMillis();
        long total=e-s;
        double d=total/1000;
        System.out.println("Time consumed = "+d+" sec");
        System.out.println("Found = "+count+" files");
    }
    
    public static void search(String dir)throws IOException
    {
        File fil = new File(dir);
        File flist[]= fil.listFiles();
        for(File s:flist)
        {
            //System.out.println(s);
            if(s.getName().contains(searchFile)){
            
                System.out.println("File found at = "+s.getAbsolutePath());
                count++;
            }
            else if(s.isDirectory()){
                //System.out.println("Searching in:"+s.getName());
                search(s.getPath());
            }
        }
        
    }
    

Program to List all drives of System

FileDemo7.java

import java.io.*; class FileDemo1{ public static void main(String ar[])throws IOException { File[] drives=File.listRoots(); for(File f:drives){ System.out.println(f); } System.out.println(""+new java.util.Date()); } }

Using JPQL in JPA

This example is using JPQL and executing select query to get multiple result from table. Here Employee is the name of entity class not a table name in database and emp is a alias for Employee entity. Query object is used to represent a query and it has getResultList method that returns list of multiple entities for each row fetched from database using JPA.


import java.util.*;
import javax.persistence.*;
public class JavaApp2
{
    public static void main(String ar[]){
        
        EntityManagerFactory emf=Persistence.createEntityManagerFactory("persistunit");
        EntityManager em=emf.createEntityManager();
        Query q=em.createQuery("SELECT OBJECT(emp) FROM Employee emp");
        List<entities.Employee> rl=q.getResultList();
        for(entities.Employee e:rl){
            System.out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - ");
            System.out.println("\t"+e.getId()+"\t"+e.getName()+"\t"+e.getSalary()+"\t"+e.getDesignation());
        }
    }
}

Generating Primary keys in JPA 

JApplet

Like awt’s Applet swing also provides the class JApplet to create the applet that may contains the swing components. JApplet has some enhanced features. The JApplet class is the subclass of Applet. JApplet support for adding menus and menu items. Default layout out of JApplet is border layout while in Applet default layout is FlowLayout.

Painting in JApplet is not as like Applet class. Paint code can not be placed directly to paint something.
//
// An example of the JApplet class.  For use with the applet.html file.
//

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
/*
 *<applet code="JAppletDemo" width=300 height=250>
</applet>
 */
public class JAppletDemo extends JApplet {
  public void init() {
    JPanel p = new JPanel();
    p.setBorder(BorderFactory.createTitledBorder("Login"));
    p.setBackground(new Color(0xCCFFCC));
    p.setLayout(new GridLayout(2, 2, 2, 2));
    p.add(new JLabel("Username"));
    p.add(new JTextField(10));
    p.add(new JLabel("Password"));
    p.add(new JPasswordField(10));
    Container content = getContentPane();
    content.setLayout(new FlowLayout());
    content.add(p);
  }
}
















Swing : Menu

JMenu is the standard menu that may have various JMenuItems. JMunu are placed into JMenuBar. and JMenuBar is added to the JFrame using setMenuBar method. you can add ActionListener to JMenuItem to deal with events. 

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

class MenuDemo
{
    public static void main(String ar[])
    {
        JFrame frame=new JFrame("Menus");
        
        JMenu file=new JMenu("File");
        file.setMnemonic(KeyEvent.VK_F);
        
        
        JMenu edit=new JMenu("Edit");
        JMenu view=new JMenu("View");
        JMenu help=new JMenu("Help");
        
        file.add(new JMenuItem("Open"));
        file.add(new JMenuItem("New"));
        file.addSeparator(  );
        //add separator
        file.add(new JMenuItem("Save"));
        file.add(new JMenuItem("Save As"));
        JMenuItem exit=new JMenuItem("Exit");
        exit.addActionListener(new ActionListener(  ) {
       public void actionPerformed(ActionEvent e) { System.exit(0); }
        });
        
        file.add(exit);
        
        edit.add(new JMenuItem("Copy"));
        edit.add(new JMenuItem("Peste"));
        edit.add(new JMenuItem("Cut"));
        edit.add(new JMenuItem("Find"));
        edit.add(new JMenuItem("Replace"));
        
        view.add(new JMenuItem("wer"));
        view.add(new JMenuItem("sgfsd"));
        view.add(new JMenuItem("sdfgds"));
        
        JMenuBar menubar=new JMenuBar();
        menubar.add(file);
        menubar.add(edit);
        menubar.add(view);
        menubar.add(help);
        
        frame.setJMenuBar(menubar);
        
        frame.setBounds(200,100,400,300);
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setVisible(true);

    }
}

Popular Posts