| Download
java source for jdbc postgresql command-line demo
Project: Earth Science
Path: pgjar/JDBCExample.java
Views: 316import java.sql.DriverManager;1import java.sql.Connection;2import java.sql.SQLException;3import java.sql.Statement;4import java.sql.ResultSet;56public class JDBCExample {78public static void main(String[] argv) {910System.out.println("-------- PostgreSQL " +11"JDBC Connection Testing ------------");1213try {1415Class.forName("org.postgresql.Driver");1617} catch (ClassNotFoundException e) {1819System.out.println("Where is your PostgreSQL JDBC Driver? " +20"Include in your library path!");21e.printStackTrace();22return;2324}2526System.out.println("PostgreSQL JDBC Driver Registered.");2728Connection connection = null;29Statement stmt = null;3031try {3233connection = DriverManager.getConnection(34"jdbc:postgresql://127.0.0.1:15432/test", "user",35"");36String sql = "SELECT * from people";37stmt = connection.createStatement();38ResultSet rs = stmt.executeQuery(sql);39//STEP 5: Extract data from result set40while (rs.next()) {41//Retrieve by column name42String name = rs.getString("name");43int age = rs.getInt("age");4445//Display values46System.out.print("Age: " + age);47System.out.println(", Name: " + name);48}49rs.close();5051} catch (SQLException e) {5253System.out.println("Connection Failed. Check output console");54e.printStackTrace();55return;5657}5859if (connection != null) {60System.out.println("Connection test succeeded.");61} else {62System.out.println("Failed to make connection.");63}64}6566}676869