postgresql java的一些例子

postgresql :http://www.postgresql.org/

pgadmin3:http://www.pgadmin.org/     //postgresql的可视化管理软件,类似于mysql的sqlyog

postgresql jdbc :http://jdbc.postgresql.org/

postgresql jdbc interface :http://jdbc.postgresql.org/documentation/head/index.html

 

一个小例子:

第一步:获得已有数据库的一个连接

1. load driver

2.getConnection

注册完Driver后,就可以使用DriverManager的方法了,这个可以具体参见jdk中的解释

Class.forName( "org.postgresql.Driver" ).newInstance();
                 
String url = "jdbc:postgresql://localhost:5432/kddcup2012" ;
                 
conn= DriverManager.getConnection(url, user , password );

url可以有三种形式:

jdbc:postgresql:database
jdbc:postgresql://host/database
jdbc:postgresql://host:port/database

而得到一个连接也有很多方法,最简单的就是像上面代码中的方法:

Connection db = DriverManager.getConnection(url, username, password);

例如,可以直接把username和password写到url中:

String ur= "jdbc:postgresql://localhost/test?user=fred&password=secret&ssl=true";
Connection conn = DriverManager.getConnection(url);

还可以设置Properties对象

String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user","fred");
props.setProperty("password","secret");
props.setProperty("ssl","true");
Connection conn = DriverManager.getConnection(url, props);

以上两个方法都得到了一个ssh连接。

第二步,进行数据库操作

当获得数据库连接后就可以进行数据操作了,下面的部分会多一些简单的小例子,大多来自jdbc interface:

1.简单的查询语句1,使用statement

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM mytable WHERE columnfoo = 500");
while (rs.next()) {
    System.out.print("Column 1 returned ");
    System.out.println(rs.getString(1));
}
rs.close();
st.close();

还可以使用prepareStatement,对sql语句进行变量的填充

int foovalue = 500;
PreparedStatement st = conn.prepareStatement("SELECT * FROM mytable WHERE columnfoo = ?");
st.setInt(1, foovalue);
ResultSet rs = st.executeQuery();
while (rs.next()) {
    System.out.print("Column 1 returned ");
    System.out.println(rs.getString(1));
}
rs.close();
st.close()

注:?代表变量赋值的地方,变量索引从1开始

 2.使用cursor,来分页读取ResultSet,也就是说不用一次把所有查询结果提入内存。

 1 conn.setAutoCommit(false);
 2 Statement st = conn.createStatement();
 3 
 4 // Turn use of the cursor on.
 5 st.setFetchSize(50);
 6 ResultSet rs = st.executeQuery("SELECT * FROM mytable");
 7 while (rs.next()) {
 8    System.out.print("a row was returned.");
 9 }
10 rs.close();
11 
12 // Turn the cursor off.
13 st.setFetchSize(0);
14 rs = st.executeQuery("SELECT * FROM mytable");
15 while (rs.next()) {
16    System.out.print("many rows were returned.");
17 }
18 rs.close();
19 st.close();

这个操作是隐式的,也就是说并不需要在程序逻辑上有什么显著的改变,它只是改变了运行的机制,也就是说在7-9行中,rs先查询50个结果,然后在while中运行50次,再向下查询50个结果,在运行50次while里的操作。而不用cursor时,rs会一次将所有结果都读入内存,如果返回的结果集特别大时这是无法运行的。

使用cursor需要几个条件:

(1) 使用V3 protocol,在7.4版本以后是默认设置

(2) Connection必须不是AutoCommit的,代码中第1行的设置:conn.setAutoCommit(false);

(3) Statement创建ResultSet时,必须使用ResultSet.TYPE_FORWARD_ONLY选项,这个设置时默认的

(4) query必须是一个单独的Statement,不能是多个Statement的总和。

(5) 另外还要设置Fetch的大小,在代码中第5行中设置,当将fetch的大小设置为0时,则表示一次全部读入。

3. 简单的Insert,Update,Delete等

在postgresql中,这些操作都需要使用PreparedStatement,就算是不需要变量的sql串。

    public  int Delete(Connection conn)
    {
        int rowsDeleted=0;
        PreparedStatement st;
        try {
            st = conn.prepareStatement("DELETE FROM mytable WHERE columnfoo = 500");
            rowsDeleted= st.executeUpdate();
        st.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return rowsDeleted;
    }
    public int Insert(Connection conn)
    {
        int rowsInsert=0;
        PreparedStatement st;
        try {
            st = conn.prepareStatement("INSERT INTO mytable(columnfoo,value) values(?,?)");
            st.setInt(1, 500);
            st.setDouble(2, 0.5);
            rowsInsert= st.executeUpdate();
        st.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return rowsInsert;        
    }

代码中写了两个简单的Insert和Delete例子,Update与其类似。

下面是一个最最简单的DBHelper

 1 package wzy.db;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.PreparedStatement;
 6 import java.sql.ResultSet;
 7 import java.sql.SQLException;
 8 import java.sql.Statement;
 9 
10 public class DataHelper {
11     
12     public static Connection NewConnection(String database,String user,String password)
13     {
14         Connection conn=null;
15          try {
16                  Class.forName( "org.postgresql.Driver" ).newInstance();
17                  
18                  String url = "jdbc:postgresql://localhost:5432/"+database ;
19                  
20                  conn= DriverManager.getConnection(url, user , password );
21 
22         } catch (InstantiationException e) {
23             e.printStackTrace();
24         } catch (IllegalAccessException e) {
25             e.printStackTrace();
26         } catch (ClassNotFoundException e) {
27             e.printStackTrace();
28         } catch (SQLException e) {
29             e.printStackTrace();
30         }
31         return conn;
32     }
33     public static ResultSet Select(Connection conn,String sql)
34     {
35         Statement st;
36         ResultSet rs=null;
37         try {
38             st = conn.createStatement();
39             rs=st.executeQuery(sql);
40         } catch (SQLException e) {
41             e.printStackTrace();
42         }
43         return rs;
44     }
45     public static boolean InsertOrDeleteOrUpdate(Connection conn,String sql)
46     {
47         int row=0;
48         try {
49             PreparedStatement pst=conn.prepareStatement(sql);
50             row=pst.executeUpdate();
51             
52         } catch (SQLException e) {
53             // TODO Auto-generated catch block
54             e.printStackTrace();
55         }
56         return row>0;
57     }
58     public static boolean InsertOrDeleteOrUpdate(PreparedStatement pst) throws SQLException
59     {
60         return pst.executeUpdate()>0;
61     }
62 }

 

posted @ 2013-07-08 03:20  bird_beginning  阅读(1669)  评论(0编辑  收藏  举报