Tuesday 22 September 2015

JDBC-EAsy codes Ass1 -PL1

//content is wrapped so actual see that below comments must remain comments
import java.sql.*;

class Ass1_final
{
    public static void main(String args[])
    {
    try
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/data1","user1","user1");
        System.out.println("Connection Success");
        PreparedStatement ps = conn.prepareStatement("CREATE TABLE COMP (NAME VARCHAR(20),QTY INT(5),PRICE DOUBLE(10,4))");//CREATE TABLE table_name (column_name column_type);
        ps.executeUpdate();
        System.out.println("Tbale created and data is inserting ...");
        PreparedStatement ps1 = conn.prepareStatement("INSERT INTO COMP VALUES(?,?,?)");//ps1
        //Set the values that will replace quesetion marks
        String name="DELL";
        int qty =1;
        double price= 45000.45;
        // now replace ?'s of PS1
        ps1.setString(1,name);
        ps1.setInt(2,qty);
        ps1.setDouble(3,price);
        ps1.executeUpdate();
        System.out.println("values are inserted ");
       
        PreparedStatement ps2 = conn.prepareStatement("UPDATE  COMP SET QTY=QTY+1 WHERE NAME='DELL' ");//update
        ps2.executeUpdate();
        System.out.println("Qty updated by 1 ...");
       
        PreparedStatement ps3 = conn.prepareStatement("SELECT * FROM COMP");//display......
        ResultSet rs=ps3.executeQuery();
       
        while(rs.next())
        {
                System.out.print("NAME" + "\t"+rs.getString("NAME"));
                System.out.print("QTY" + "\t"+rs.getInt("QTY"));
                System.out.println("NAME" +"\t"+ rs.getDouble("PRICE"));
        }
       
        PreparedStatement ps4 = conn.prepareStatement("UPDATE  COMP SET QTY=QTY+1 WHERE NAME='DELL' ");//update
        ps4.executeUpdate();
       
        PreparedStatement ps5 = conn.prepareStatement("DROP TABLE COMP ");//update
        ps5.executeUpdate();
       
        System.out.println("table dropped or deleted..");
       
       
        rs.close();
        conn.close();
    }
    catch(Exception e)
    {
        System.out.println(e.getMessage());
    }
   
    }


}

No comments:

Post a Comment