我是靠谱客的博主 沉静紫菜,这篇文章主要介绍JDBC连接postgresql例子,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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(); } } }

最后

以上就是沉静紫菜最近收集整理的关于JDBC连接postgresql例子的全部内容,更多相关JDBC连接postgresql例子内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(65)

评论列表共有 0 条评论

立即
投稿
返回
顶部