您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關怎么在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中利用JDBC連接postgresql數據庫,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。