Friday, January 9, 2015

Java using GUI and Connect to a Database and Java Table



Draw text using GUI

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel
{
   public void paint(Graphics g) 
  {
      Graphics2D g2 = (Graphics2D)g;
      g2.setRenderingHint(RenderingHints.key_antialiasing,
      RenderingHints.Value_antialias_on);
      Font font = new Font("Serif", Font.plain, 96);
      g2.setFont(font);
      g2.drawString("Text", 40, 120);
   }
   public static void main(String[] args) 
  {
      JFrame f = new JFrame();
      f.getContentPane().add(new Main());
      f.setSize(300, 200);
      f.setVisible(true);
   }
}

Connect to a Database

import java.sql.*;
public class jdbcConn 
{
   public static void main(String[] args) 
  {
      try 
      {
         Class.forName("org.apache.derby.jdbc.ClientDriver");
      }
      catch(ClassNotFoundException e) 
     {
         System.out.println("Class not found "+ e);
      }
      System.out.println("Jdbc Class found");
      int no_of_rows = 0;
      try 
      {
         Connection con = DriverManager.getConnection
         ("jdbc:derby://localhost:1527/testDb","username","password");  
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery("Select * from employee");
         while (rs.next()) 
          {
            no_of_rows++;
           }
       System.out.println("There are "+ no_of_rows + " record in the table");
           }
      catch(SQLException e)
      {
         System.out.println("SQL exception occured" + e);
      }
   }
}

Edit Table

import java.sql.*;
public class jdbcConn 
{
   public static void main(String[] args) throws Exception
  {
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection
      ("jdbc:derby://localhost:1527/testDb","username","password");
      Statement stmt = con.createStatement();
      String query ="Create table employees  (id Integer    primary key, first_name Char(50),last_name Char(75))";
      stmt.execute(query);
      System.out.println("Employee table created");
      String query1 = "aLTER TABLE employees Add 
      address Char(100) ";
      String query2 = "ALTER TABLE employees Drop 
      Column last_name";
      stmt.execute(query1);
      stmt.execute(query2);
      System.out.println("Address column added to the table 
      & last_name column removed from the table");
      String query3 = "drop table employees";
      stmt.execute(query3);
      System.out.println("Employees table removed");
   }       
}

No comments:

Post a Comment