Java連接postgresql數(shù)據(jù)庫(kù)的示例代碼
本文介紹了Java連接postgresql數(shù)據(jù)庫(kù)的示例代碼,分享給大家,具體如下:
1.下載驅(qū)動(dòng)jar
下載地址:https://jdbc.postgresql.org/download.html
2.導(dǎo)入jar包
新建lib文件夾,將下載的jar驅(qū)動(dòng)包拖到文件夾中。

將jar驅(qū)動(dòng)包添加到Libraries


3.程序代碼如下:HelloWorld.java
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數(shù)據(jù)庫(kù)"+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);
}
}
}
}
}
運(yùn)行結(jié)果:

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Hadoop源碼分析一架構(gòu)關(guān)系簡(jiǎn)介
本篇是Hadoop源碼分析系列文章第一篇,主要介紹一下Hadoop的基礎(chǔ)簡(jiǎn)介以及框架關(guān)系,后續(xù)本系列文章會(huì)持續(xù)更新,有需要的朋友可以借鑒參考下2021-09-09
java calendar 日期實(shí)現(xiàn)不斷加一天的代碼
這篇文章主要介紹了java calendar 日期實(shí)現(xiàn)不斷加一天的代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10
Spring-Boot 訪問(wèn)外部接口的方案總結(jié)
在Spring-Boot項(xiàng)目開(kāi)發(fā)中,存在著本模塊的代碼需要訪問(wèn)外面模塊接口,或外部url鏈接的需求,針對(duì)這一需求目前存在著三種解決方案,下面將對(duì)這三種方案進(jìn)行整理和說(shuō)明,對(duì)Spring-Boot 訪問(wèn)外部接口方案感興趣的朋友跟隨小編一起看看吧2022-12-12

