表和数据:
CREATE TABLE weather (
city varchar(80),
temp_lo int, -- low temperature
temp_hi int, -- high temperature
prcp real, -- average temperature
date date
);
insert into weather values ('Wuhan', 15, 30, 25.5, '2010-09-21');
insert into weather values ('Beijing', 10, 22, 15.3, '2010-09-22');
insert into weather values ('Shanghai', 17, 35, 28.6, '2010-09-22');
insert into weather values ('Guangzhou', 30, 36, 32.7, '2010-09-22');
insert into weather values ('Xiamen', 24, 32, 30.3, '2010-09-22');
示例类:
public class TestConnPostgreSQL {
public static void main(String[] args) {
try {
Class.forName("org.postgresql.Driver").newInstance();
String url = "jdbc:postgresql://localhost:5432/testdb";
Connection conn = DriverManager.getConnection(url, "postgres", "postgres");
Statement st = conn.createStatement();
String sql = "select * from weather";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
System.out.print( rs.getString("city") + "\t");
System.out.print( rs.getString("temp_lo") + "\t");
System.out.print( rs.getString("temp_hi") + "\t");
System.out.print( rs.getString("prcp") + "\t");
System.out.println( rs.getString("date"));
}
rs.close();
st.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出结果: