Java連接postgresql數(shù)據(jù)庫的示例代碼
更新時間:2017年08月17日 16:27:33 作者:迪米特
本篇文章主要介紹了Java連接postgresql數(shù)據(jù)庫的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
本文介紹了Java連接postgresql數(shù)據(jù)庫的示例代碼,分享給大家,具體如下:
1.下載驅(qū)動jar
下載地址:https://jdbc.postgresql.org/download.html
2.導(dǎo)入jar包
新建lib文件夾,將下載的jar驅(qū)動包拖到文件夾中。

將jar驅(qū)動包添加到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ù)庫"+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);
}
}
}
}
}
運行結(jié)果:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java calendar 日期實現(xiàn)不斷加一天的代碼
這篇文章主要介紹了java calendar 日期實現(xiàn)不斷加一天的代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10

