17

I have created a set of SQL queries that modify a database, and now I want to test them.

How can I create a local and temporary PostgreSQL database to test my queries. I'm working in Java.

2
  • 2
    FWIW, I wouldn't do that part in Java. The tutorial discusses creating a DB, tables, etc. Commented Oct 30, 2011 at 13:49
  • 1
    And after setting up the database I'm sure you want to know how to connect to that database inn Java. The PostgreSQL JDBC Docs will tell you. Commented Oct 30, 2011 at 14:20

4 Answers 4

19

You CAN create and drop PostgreSQL db's via Java using the Statement object.

Example:

Connection c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/", "username", "password");
Statement statement = c.createStatement();
statement.executeUpdate("DROP DATABASE mydb");

See the following link for a good starting point:

http://www.jvmhost.com/articles/create-drop-databases-dynamically-java-jsp-code

Sign up to request clarification or add additional context in comments.

2 Comments

This one does not work as Java JDBC throws exception right after DriverManager.getConnection(...) because if database name is not specified it will use the username as default database. jdbc.postgresql.org/documentation/head/connect.html
This is clearly wrong since it requires a database named user to exist.
18

Creating a database is simple enough once your database cluster is in place.
Connect to the maintenance database postgres (installed by default) and issue

CREATE DATABASE testdb;

The database will be created and you can connect to it now. Of course you need to have the necessary privileges to create a database.

Comments

-5

You can see her how to create database Hope this help

  1. What you do is connect to localhost
  2. create an sql "create database your_db"
  3. execute

http://www.tutorialspoint.com/jdbc/jdbc-create-database.htm

You must connect first to the localhost

//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/";

   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);

      //STEP 4: Execute a query
      System.out.println("Creating database...");
      stmt = conn.createStatement();

      String sql = "CREATE DATABASE STUDENTS";
      stmt.executeUpdate(sql);
      System.out.println("Database created successfully...");
   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      }// nothing we can do
  try{
     if(conn!=null)
        conn.close();
  }catch(SQLException se){
     se.printStackTrace();
      }//end finally try
   }//end try
  System.out.println("Goodbye!");
}//end main
}//end JDBCExample

2 Comments

Please expand your answer further than just giving a link. See here for further reasoning.
The question is about Postgres, not MySQL
-10

Your question is little bit wrong,with Java code you cannot create a database,you can just connect to a database.

First of all you need to create a database in PgAdminIII.

Here is the code which will help you to create table in postgresql database through JAVA

    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 MY_TABLE "+ 
             "(ID INT NOT NULL,"
             + "NAME TEXT       NOT NULL,"
             +     "AGE             INT                  NOT NULL)";




     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");
    }
    }

For complete reference:http://kodingpoint.blogspot.in/2014/01/java-postgresql-connectivity-example.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.