Tuesday, December 28, 2010

JDBC: creating tables and inserting values to tables dynamically sample code

I believe my previously written "JDBC" post has given you a basic idea to start JDBC in a windows environment. So here I go again under the same topic but this time the post will be limited to a code. In previous post I have given codes to create a database dynamically and connecting to a database. This code shows how to create tables inside that database and inserting values dynamically into that newly created table.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.Scanner;

public class Myjdbc {

 public static void main(String args[]) {

  System.out.println("now we are going to connect with a database ");

  try {

   Class.forName("com.mysql.jdbc.Driver");

   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "123");
   Statement st = con.createStatement();

   System.out.println("connection has been made ");

   Scanner scanner = new Scanner(System.in);
   System.out.println("please enter table name ");
   String tableName = scanner.next();

   String strr = null;

   System.out.println("Enter no of columns you like to use: ");
   int noc = scanner.nextInt();

   for (int i = 1; i <= noc; i++) {
    BufferedReader bf = new BufferedReader(new InputStreamReader(
      System.in));
    System.out.println("Enter column name with type ");
    String s1 = bf.readLine();
    if (strr == null) {
     strr = s1;

    } else {
     strr = strr + s1;

    }

   }

   st.executeUpdate("create table " + tableName + "(" + strr + ")");
   System.out.println("your table " + tableName
     + " has been created!!!");

   ResultSet rs = st.executeQuery("SELECT * FROM " + tableName);
   ResultSetMetaData rsmd = rs.getMetaData();
   int NumOfCol = rsmd.getColumnCount();
   System.out.println("Number of Columns of your table =" + tableName
     + " " + NumOfCol);
   System.out.println("Column names are ");
   for (int i = 1; i <= NumOfCol; i++) {
    System.out.println(rsmd.getColumnName(i));
   }
   String strn = null;
   System.out.println("please enter values you need to insert");

   for (int i = 1; i <= NumOfCol; i++) {
    String s5 = scanner.next();
    if (strn == null) {
     strn = s5;

    } else
     strn = strn + s5;

   }
   System.out.println(strn);

   st.executeUpdate("insert into " + tableName + " values" + "("
     + strn + ")");
   System.out.println("your table " + tableName
     + " has been filled!!!");

   con.close();
   System.out.println("connection has been colsed ");

  }

  catch (Exception e) {

   System.out.println(e.getMessage());
  }

 }

}



2 comments :

  1. this is very helpful article,Can you help me on instertin string type value and int type value both dyanmically.

    ReplyDelete
  2. quiet complicated .............

    ReplyDelete