Sunday, February 25, 2018

Advanced Java program : JDBC Creating tables and inserting records DYNAMICALLY

//Creating tables and inserting records in a known/existing database DYNAMICALLY/i.e through Keyboard
//while the program is running

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class DynamicDatabase {

    public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException {
        // TODO Auto-generated method stub
        System.out.println("Ashutosh");
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection=DriverManager.getConnection("jdbc:mysql://localhost/mybooks","AKSingh", "ashutosh");
        Statement statement=connection.createStatement();
        Scanner scanner=new Scanner(System.in);
        System.out.println("enter table name you want to create");
        String tname= scanner.next();
        String q1="create table "+tname+"(id int, name varchar(50), salary float)";
        int x=statement.executeUpdate(q1);
        System.out.println("table is created"+tname+" "+x);
        while(true)
        {
            System.out.println("enter id");
            int id=scanner.nextInt();
            System.out.println("enter name");
            String name=scanner.next();
            System.out.println("enter salary");
            float salary=scanner.nextFloat();
            String q2="insert into "+tname+" values("+id+" ,'"+name+"',"+ salary+")";
            System.out.println(q2);
            statement.executeUpdate(q2);
            System.out.println("values are inserted succesfuly");
            System.out.println("do you want more records (yes/no)");
            String option =scanner.next();
            if(option.equals("no"))
            {
                break;
            }
       
        }
        Thread.sleep(15000);
        System.out.println("enter the table name you want to drop");
        String droptable= scanner.next();
        String q3="drop table "+droptable;
        System.out.println(q3);
        statement.executeUpdate(q3);
        System.out.println("table dropped sucessfuly");
        System.out.println("All operations completed sucessfuly");
       
       

    }

}

Thanks
Happy Programming!

No comments:

Post a Comment

Sacred Thought

28 April 2024 Today I am going to explain verse 31 - 38 chapter two for you all. There is no opportunity better than a righteous war (सत्य औ...