简体   繁体   中英

How can I create a PostgreSQL database in Java?

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.

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

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM