The Sixth Lab
JDBC for PostgreSQL
(I) Download JDBC Driver
Choose 9.2-1004 JDBC 4
You'd better create a new folder for JDBC Driver and code in this Lab.
Directly copy the jar file to the folder you created.
(II) Connect to PostgreSQL Server
Go to the folder including JDBC Driver
Copy the java file to the folder including JDBC Driver.
Change [username in your email] to your real username. Use " to quote your username.
Change [password in your email] to your real password. Use " to quote your password.
Use javac ConnectPostgreSQL.java to compile the java code.
Use java -cp .:postgresql-9.2-1004.jdbc4.jar ConnectPostgreSQL to run the code.
If you are using a different JDBC Driver, change the file name of the jar file.
The code successfully connects to PostgreSQL Sever if the console displays as follow:
Opened database successfully
...
Closed database successfully
(III) Query by using JDBC
Go to the folder including JDBC Driver
Copy the java file to the folder including JDBC Driver.
Change [username in your email] to your real username. Use " to quote your username.
Change [password in your email] to your real password. Use " to quote your password.
Use javac QueryPostgreSQL.java to compile the java code.
Use java -cp .:postgresql-9.2-1004.jdbc4.jar QueryPostgreSQL to run the code.
Now, you should be able to see the query result to the first question in Lab 5.
Learn how to execute the queries by using JDBC.
(IV) Learn java.sql Package
The syntax is DriverManager.getConnection(jdbc:postgresql:database, username, password);
A ResultSet object maintains a cursor pointing to its current row of data.
Use next() if you want to get the next row of data.
Use getString(int columnIndex) to retrieve the value of the designated column in the current row. (In String Format)
The metadata includes information like number of columns in the ResultSet.
(V) Exercise