Tuesday, 13 March 2007

PostgreSQL from home using Windows and Netbeans

Getting PostgreSQL running on your home machine

To import a database created at uni, you first need to dump the information into a file readable by PostgreSQL. To do this, in the terminal window type pg_dump -O DBNAME > FILENAME. This will create a file with the name you specified, removing the owner privelages which will make it easier to restore it on another computer.

First, download postgresql from the official website here.

Install postgresql on your local machine. It would be a good idea to use your windows login for your PostgreSQL main login to save you having to log on as a different time you access psql.

Access the command prompt and move to the \Postgresql\8.2\bin\ (this is done automatically if you load 'Command Prompt' in the newly created Postgresql folder in your start menu. To log into postgresql, type psql postgres. This will log you into PostgreSQL.

You can setup a new user from here to allow you to connect as the same username as you use at uni to keep your code as close to what you will need to run on the uni computers. To do this, type Create user USER with password 'PASSWORD' createdb; This creates your new user with the privelage to create databases. Quit PostgreSQL using the \q command.

Log back in as your new user using the command psql postgres "USER" (include the " " around username). You will be asked to enter your password. Once you are in, create a new database with the same name as the database you are working on at uni with the command create database DBNAME. Quit PostgreSQL once this is done.

Now we need to restore the database dump into your local postgresql. Make sure that the dump of your original database is in this directory, and then type psql DBNAME <>". This will imort the file into the newly created database and you're ready to connect to it. To do so, type psql DBNAME "USERNAME".

Getting netbeans set up to connect to PostgreSQL databases

Download the JDBC drivers here. Put the jar file in your Java folder (normally \Program Files\Java\).

Load up netbeans and right click on your project and go to properties. Select Libraries from the left pane and make sure you are in the compile tab. Click Add Jar/Folder and find the JDBC jar file you just saved.

To make a connection in a java method, you first need to call

Class.forName(org.postgresql.Driver);

This tells netbeans which driver to use when creating connections.
When creating a connection, the default url for a locally stored database is

jdbc:postgresql://localhost:5432/DBNAME

1 comment:

Rob Rowley said...

I need to make a couple of changes to the database as it is, so if you haven't got a new copy of the database after reading this comment (14.3.07), then you will have to do so. Also, I need to set up priveledges for James and Feng-Ming, so if you can remind me to do this when you see me in the lab, then that would be great.