Thread: Re: Use Driver to Create database?

Re: Use Driver to Create database?

From
Brendon Bentley
Date:
How to create database with JDBC on PostgreSQL RDMS:

For a complete example that works:

//-- Note that this string ends on "postgres".  That is
//   the name of the default database that can always
//   be connected to.
String dbUrl = "jdbc:postgresql://localhost:8988/postgres";
String dbDriver = "org.postgresql.Driver";
String dbUsername = "Db_test_client";
String dbPassword = "Db_test_pwd";
try { //-- Checks that database driver is loaded
     Class.forName(dbDriver);
}  catch (ClassNotFoundException ex) {
     throw new DbWriteException( ex );
}
try {
     //-- Connect to database
     Connection dbConnection =
DriverManager.getConnection(dbUrl,dbUsername,dbPassword);

     //--Make SURE auto commit is on, because you cannot
     //  add a database to a transaction block.  A trans-
     //  action block is a collection of SQL statements
     //  that are only executed when dbConnection.commit()
     //  is called.
     dbConnection.setAutoCommit(true);
     String sql = "CREATE DATABASE testDatabase";
     Statement cs = dbConnection.createStatement();
     cs.execute(sql);
     cs.close();
     dbConnection.close();

//-- If this code still fails your login account probably
//   does not have privileges to create databases


On 2006-11-19 21:42, Roland Walter wrote:
 > Charlie Kelly wrote:
 > > Is it possible to use the driver to create a new database (inside a
java
 > > program),
 > > or is it necessary to first create the database using the createdb
utility?
 > >
 > > If it is possible to use the driver, what is the correct syntax?
 > >
 >
 > There is a SQL-command for that, look here:
 >
 >
 > http://www.postgresql.org/docs/8.1/interactive/sql-createdatabase.html
 >
 > First connect to the postgres or template1 schema of the cluster, that
 > you created with initdb. Execute the "CREATE DATABASE". Reconnect to the
 > database you created.
 >
 > Regards,
 > Roland.
 > - --
 > Dipl.-Phys. Roland Walter
 > mailto: roland (dot)walter (dot) rwa (at) gmx (dot) net
 >
 > ---------------------------(end of broadcast)---------------------------
 > TIP 7: You can help support the PostgreSQL project by donating at
 >
 >                 http://www.postgresql.org/about/donate
 >