本文介绍了java连接postgresql数据库的示例代码,分享给大家,具体如下:
1.下载驱动jar
下载地址:https://jdbc.postgresql.org/download.html
2.导入jar包
新建lib文件夹,将下载的jar驱动包拖到文件夹中。
将jar驱动包添加到libraries
3.程序代码如下:helloworld.java
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
|
package test; import java.sql.connection; import java.sql.drivermanager; import java.sql.resultset; import java.sql.sqlexception; import java.sql.statement; public class helloworld { public static void main(string []args) { connection connection= null ; statement statement = null ; try { string url= "jdbc:postgresql://127.0.0.1:5432/postgis" ; string user= "postgres" ; string password = "123456" ; class .forname( "org.postgresql.driver" ); connection= drivermanager.getconnection(url, user, password); system.out.println( "是否成功连接pg数据库" +connection); string sql= "select name from test" ; statement=connection.createstatement(); resultset resultset=statement.executequery(sql); while (resultset.next()){ string name=resultset.getstring( 1 ); system.out.println(name); } } catch (exception e){ throw new runtimeexception(e); } finally { try { statement.close(); } catch (sqlexception e){ e.printstacktrace(); throw new runtimeexception(e); } finally { try { connection.close(); } catch (sqlexception e){ e.printstacktrace(); throw new runtimeexception(e); } } } } } |
运行结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/shijingjing07/p/6354487.html