Java使用JDBC連接postgresql數(shù)據(jù)庫示例
更新時間:2019年01月23日 11:30:04 作者:韓大貓
這篇文章主要介紹了Java使用JDBC連接postgresql數(shù)據(jù)庫,結合實例形式分析了jdbc連接postgresql數(shù)據(jù)庫及數(shù)值插入、更新、查詢等相關操作技巧,需要的朋友可以參考下
本文實例講述了Java使用JDBC連接postgresql數(shù)據(jù)庫。分享給大家供大家參考,具體如下:
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操作數(shù)據(jù)庫技巧總結》、《Java+MySQL數(shù)據(jù)庫程序設計總結》、《Java數(shù)據(jù)結構與算法教程》、《Java文件與目錄操作技巧匯總》、《Java操作DOM節(jié)點技巧總結》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
相關文章
springboot整合Excel填充數(shù)據(jù)代碼示例
這篇文章主要給大家介紹了關于springboot整合Excel填充數(shù)據(jù)的相關資料,文中通過代碼示例介紹的非常詳細,對大家學習或者使用springboot具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08