Java使用JDBC连接postgresql数据库示例
本文实例讲述了Java使用JDBC连接postgresql数据库。分享给大家供大家参考,具体如下:
package tool; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class PsqlConnectionTool { private String url = "jdbc:postgresql://xxx.xxx.xxx.xxx:5432/testdb"; private String username = "postgres"; private String password = "postgres"; private Connection connection = null; public Connection getConn() { try { Class.forName("org.postgresql.Driver").newInstance(); connection = DriverManager.getConnection(url, username, password); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return connection; } public ResultSet query(Connection conn, String sql) { PreparedStatement pStatement = null; ResultSet rs = null; try { pStatement = conn.prepareStatement(sql); rs = pStatement.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } return rs; } public boolean queryUpdate(Connection conn, String sql) { PreparedStatement pStatement = null; int rs = 0; try { pStatement = conn.prepareStatement(sql); rs = pStatement.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (rs > 0) { return true; } return false; } public static void main(String[] args) throws SQLException { PsqlConnectionTool pgtool = new PsqlConnectionTool(); Connection myconn = pgtool.getConn(); pgtool.queryUpdate(myconn, "insert into test values (1,'smoon','man')"); ResultSet rs = pgtool.query(myconn, "select * from test"); while(rs.next()){ int id = rs.getInt("id"); String name = rs.getString("name"); String gender = rs.getString("gender"); System.out.println("id:"+id+" 姓名:"+name+" 性别:"+gender); myconn.close(); } } }
更多关于java相关内容感兴趣的读者可查看本站专题:《Java使用JDBC操作数据库技巧总结》、《Java+MySQL数据库程序设计总结》、《Java数据结构与算法教程》、《Java文件与目录操作技巧汇总》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。
赞 (0)