Pageviews

Thursday 23 January 2014

How to create a table in Postgresql database through Java

by Unknown  |  in Database at  Thursday, January 23, 2014

In the previous post,I had discussed about the connectivity of Java and Postgresql,now in this post I am going to discuss of how to create a table in Postgresql database:

Here is our PgAdminIII before making a table:


Here is the code snippet of creating a table in Postgresql database:


package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Database {

   public static void main(String args[]) {
        try {
            Connection c = null;
            Statement stmt = null;
         
            try {
               Class.forName("org.postgresql.Driver");
               c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/kanwar","postgres", "osm");
            } catch (Exception e) {
               e.printStackTrace();
               System.err.println(e.getClass().getName()+": "+e.getMessage());
               System.exit(0);
            }
            System.out.println("Opened database successfully");
              try {
                  stmt = c.createStatement();
              } catch (SQLException ex) {
                  Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
              }
         String sql = "CREATE TABLE GARAGE "+ "(NAME TEXT       NOT NULL,"
                 +     "AGE             INT                  NOT NULL)";//Here I had created a new table named 'Garage' using simple sql statement
       
       
       
       
         stmt.executeUpdate(sql);
         stmt.close();
         c.close();
        } catch (SQLException ex) {
            Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch(Exception e)
        {
   System.err.println( e.getClass().getName()+": "+ e.getMessage() );
   System.exit(0);
        }
        System.out.println("Table Created Successfully");
           }
}
    Now have a look at your PgAdminIII after the table creation.



Thats it you had created a new table in Postgresql database.

1 comment:

Proudly Powered by Blogger.