安装
在我们开始在Java程序中使用PostgreSQL之前,我们需要确保在机器上设置PostgreSQL JDBC和Java.您可以在计算机上查看Java安装Java教程.现在让我们检查一下如何设置PostgreSQL JDBC驱动程序.
下载最新版本的 postgresql-(VERSION)来自 postgresql-jdbc 存储库的.jdbc.jar .
在类路径中添加下载的jar文件 postgresql-(VERSION).jdbc.jar ,或者您可以将它与-classpath选项一起使用如下面的示例中所述.
以下部分假设您对Java JDBC概念知之甚少.如果您没有,则建议花费一半时间使用 JDBC教程熟悉下面解释的概念.
连接到数据库
以下Java代码显示了如何连接到现有数据库.如果数据库不存在,那么它将被创建,最后将返回一个数据库对象.
import java.sql.Connection;import java.sql.DriverManager;public class PostgreSQLJDBC { public static void main(String args[]) { Connection c = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/testdb", "postgres", "123"); } catch (Exception e) { e.printStackTrace(); System.err.println(e.getClass().getName()+": "+e.getMessage()); System.exit(0); } System.out.println("Opened database successfully"); }}
在编译并运行上述程序之前,找到你的 pg_hba.conf 文件PostgreSQL安装目录并添加以下行 :
# IPv4 local connections:host all all 127.0.0.1/32 md5
您可以使用以下命令启动/重新启动postgres服务器,如果它没有运行 :
[root@host]# service postgresql restartStopping postgresql service: [ OK ]Starting postgresql service: [ OK ]
现在,让我们编译并运行上面的程序来连接testdb.在这里,我们使用 postgres 作为用户ID,使用 123 作为密码来访问数据库.您可以根据数据库配置和设置更改此设置.我们还假设当前版本的JDBC驱动程序 postgresql-9.2-1002.jdbc3.jar 在当前路径中可用.
C:\JavaPostgresIntegration>javac PostgreSQLJDBC.javaC:\JavaPostgresIntegration>java -cp c:\tools\postgresql-9.2-1002.jdbc3.jar;C:\JavaPostgresIntegration PostgreSQLJDBCOpen database successfully
创建表
以下Java程序将用于创建表以前打开过数据库确保目标数据库中没有此表.
import java.sql.*;import java.sql.Connection;import java.sql.DriverManager;import java.sql.Statement;public class PostgreSQLJDBC { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/testdb", "manisha", "123"); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "CREATE TABLE COMPANY " + "(ID INT PRIMARY KEY NOT NULL," + " NAME TEXT NOT NULL, " + " AGE INT NOT NULL, " + " ADDRESS CHAR(50), " + " SALARY REAL)"; stmt.executeUpdate(sql); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName()+": "+ e.getMessage() ); System.exit(0); } System.out.println("Table created successfully"); }}
编译并执行程序时,它将在 testdb 数据库并将显示以下两行 :
Opened database successfullyTable created successfully
INSERT操作
以下Java程序显示了我们如何在上面示例中创建的COMPANY表中创建记录 :
import java.sql.Connection;import java.sql.DriverManager;import java.sql.Statement;public class PostgreSQLJDBC { public static void main(String args[]) { Connection c = null; Statement stmt = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/testdb", "manisha", "123"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (1, 'Paul', 32, 'California', 20000.00 );"; stmt.executeUpdate(sql); sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (2, 'Allen', 25, 'Texas', 15000.00 );"; stmt.executeUpdate(sql); sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );"; stmt.executeUpdate(sql); sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " + "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"; stmt.executeUpdate(sql); stmt.close(); c.commit(); c.close(); } catch (Exception e) { System.err.println( e.getClass().getName()+": "+ e.getMessage() ); System.exit(0); } System.out.println("Records created successfully"); }}
编译并执行上述程序时,它将在COMPANY表中创建给定记录并显示以下内容两行 :
Opened database successfullyRecords created successfully
SELECT操作
以下Java程序显示了我们如何从上面示例中创建的COMPANY表中获取和显示记录 :
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class PostgreSQLJDBC { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/testdb", "manisha", "123"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" ); while ( rs.next() ) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); String address = rs.getString("address"); float salary = rs.getFloat("salary"); System.out.println( "ID = " + id ); System.out.println( "NAME = " + name ); System.out.println( "AGE = " + age ); System.out.println( "ADDRESS = " + address ); System.out.println( "SALARY = " + salary ); System.out.println(); } rs.close(); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName()+": "+ e.getMessage() ); System.exit(0); } System.out.println("Operation done successfully"); }}
编译并执行程序时,它将产生以下结果 :
Opened database successfullyID = 1NAME = PaulAGE = 32ADDRESS = CaliforniaSALARY = 20000.0ID = 2NAME = AllenAGE = 25ADDRESS = TexasSALARY = 15000.0ID = 3NAME = TeddyAGE = 23ADDRESS = NorwaySALARY = 20000.0ID = 4NAME = MarkAGE = 25ADDRESS = Rich-MondSALARY = 65000.0Operation done successfully
UPDATE操作
以下Java代码显示了我们如何使用UPDATE语句更新任何记录,然后从我们的COMPANY表中获取并显示更新的记录 :
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class PostgreSQLJDBC { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/testdb", "manisha", "123"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;"; stmt.executeUpdate(sql); c.commit(); ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" ); while ( rs.next() ) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); String address = rs.getString("address"); float salary = rs.getFloat("salary"); System.out.println( "ID = " + id ); System.out.println( "NAME = " + name ); System.out.println( "AGE = " + age ); System.out.println( "ADDRESS = " + address ); System.out.println( "SALARY = " + salary ); System.out.println(); } rs.close(); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName()+": "+ e.getMessage() ); System.exit(0); } System.out.println("Operation done successfully"); }}
编译并执行程序时,它将产生以下结果 :
Opened database successfullyID = 2NAME = AllenAGE = 25ADDRESS = TexasSALARY = 15000.0ID = 3NAME = TeddyAGE = 23ADDRESS = NorwaySALARY = 20000.0ID = 4NAME = MarkAGE = 25ADDRESS = Rich-MondSALARY = 65000.0ID = 1NAME = PaulAGE = 32ADDRESS = CaliforniaSALARY = 25000.0Operation done successfully
DELETE操作
以下Java代码显示了我们如何使用DELETE语句删除任何记录,然后从COMPANY表中删除并显示剩余记录 :
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class PostgreSQLJDBC6 { public static void main( String args[] ) { Connection c = null; Statement stmt = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/testdb", "manisha", "123"); c.setAutoCommit(false); System.out.println("Opened database successfully"); stmt = c.createStatement(); String sql = "DELETE from COMPANY where ID = 2;"; stmt.executeUpdate(sql); c.commit(); ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" ); while ( rs.next() ) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); String address = rs.getString("address"); float salary = rs.getFloat("salary"); System.out.println( "ID = " + id ); System.out.println( "NAME = " + name ); System.out.println( "AGE = " + age ); System.out.println( "ADDRESS = " + address ); System.out.println( "SALARY = " + salary ); System.out.println(); } rs.close(); stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName()+": "+ e.getMessage() ); System.exit(0); } System.out.println("Operation done successfully"); }}
编译并执行程序时,它将产生以下结果 :
Opened database successfullyID = 3NAME = TeddyAGE = 23ADDRESS = NorwaySALARY = 20000.0ID = 4NAME = MarkAGE = 25ADDRESS = Rich-MondSALARY = 65000.0ID = 1NAME = PaulAGE = 32ADDRESS = CaliforniaSALARY = 25000.0Operation done successfully