Java使用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(); } } }
更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java使用JDBC操作數(shù)據(jù)庫技巧總結(jié)》、《Java+MySQL數(shù)據(jù)庫程序設(shè)計總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java文件與目錄操作技巧匯總》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
springboot整合Excel填充數(shù)據(jù)代碼示例
這篇文章主要給大家介紹了關(guān)于springboot整合Excel填充數(shù)據(jù)的相關(guān)資料,文中通過代碼示例介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用springboot具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08java多線程編程之Synchronized關(guān)鍵字詳解
這篇文章主要為大家詳細(xì)介紹了java多線程編程之Synchronized關(guān)鍵字,感興趣的朋友可以參考一下2016-05-05詳解如何利用jasypt實(shí)現(xiàn)配置文件加密
Jasypt?(Java?Simplified?Encryption)?是一個?java?庫,它允許開發(fā)人員以最小的成本將基本的加密功能添加到項目中,而無需深入了解密碼學(xué)的工作原理。本文將利用jasypt實(shí)現(xiàn)配置文件加密,感興趣的可以學(xué)習(xí)一下2022-07-07