1.下载PostgreSQL JDBC驱动:

http://jdbc.postgresql.org/download.html

2. 新建一个java项目,导入下载的jar包Add External JARs

3. 连接代码如下:

import java.sql.*;
import java.io.*;
import java.util.StringTokenizer;
import java.util.Properties;
import java.util.Random; /**
* Class <b>DBWrapper</b> contains
* wrapper routines for using JDBC
* to access the database.
*
* @author luwei
* @version 1.0
*/
public class DBWrapper
{ private static int CONNECTION_RETRIES = 10;
private static int QUERY_RETRIES = 10; private String dbUrl;
private String username;
private String password;
private String jdbcClassName;
private Connection dbCon; private boolean hasError = false;
private String errorString = null;
private static DBWrapper myInstance = null; /**
* DBWrapper constructor
*/
public DBWrapper() {} /**
* DBWrapper conscrutor
* @param inUrl String url of database
* @param inJdbcClassName String containing name of jdbc driver
* @param inUserName String containing database username
* @param inPassWord String containing database password
*/ public DBWrapper( String inUrl, String inJdbcClassName, String inUserName, String inPassWord )
throws Exception {
dbUrl = inUrl;
jdbcClassName = inJdbcClassName;
username = inUserName;
password = inPassWord;
connect();
} /**
* connectAsDefaultCteLibrary()
* Create a connection to the CTE library using the default connection parameters.
* @return void
*/
public void connectAsDefaultDatabase()
throws Exception {
myInstance.connect("jdbc:postgresql://localhost:5432/postgres",
"org.postgresql.Driver", "postgres", "741613551"); } /**
* closeConnections closes any currently open connections
* @return void
*/
private void closeConnections()
throws Exception {
if (dbCon!=null) {
dbCon.close();
}
} /**
* DBWrapper Instance()
* Get a singleton instance of the DBWrapper object.
* @return DBWrapper
*/
public static DBWrapper Instance()
throws Exception {
if (myInstance == null) {
myInstance = new DBWrapper();
myInstance.connectAsDefaultDatabase();
}
return myInstance;
} /**
* boolean connect()
* Connect to a database using the parameters supplied in the constructor.
* @return boolean
*/
private boolean connect()
throws Exception { boolean opened = false; DriverManager.registerDriver(new org.postgresql.Driver());
// Try to open a connection the database.
int retry = 0;
while(retry++ < CONNECTION_RETRIES){
Class.forName(jdbcClassName);
dbCon = DriverManager.getConnection(dbUrl,username,password);
break;
}
if(retry < CONNECTION_RETRIES)opened=true;
return opened;
} /**
* boolean connect()
* Connect to a JDBC datasource without using the parameters supplied in the constructor.
* @param inUrl String url of database
* @param inJdbcClassName String containing name of jdbc driver
* @param inUserName String containing database username
* @param inPassWord String containing database password
* @return boolean
*/
public boolean connect( String inUrl, String inJdbcClassName, String inUserName, String inPassWord )
throws Exception {
dbUrl = inUrl;
jdbcClassName = inJdbcClassName;
username = inUserName;
password = inPassWord;
closeConnections(); return connect();
} /**
* ResultSet runQuery()
* Executes a query and returns a resultset.
*
* @param String containing a SQL statement
* @return ResultSet
*/
public ResultSet runQuery( String sqlQuery )
throws Exception {
Statement statement=dbCon.createStatement();
ResultSet resultSet=statement.executeQuery(sqlQuery);
return resultSet;
} /**
* boolean runUpdate()
* Executes an update and returns true of successfully executed.
*
* @param String containing a SQL statement
* @return boolean
*/
public boolean runUpdate( String sqlQuery )
throws Exception {
Statement ps=dbCon.createStatement();
boolean wasExecuted = false;
int retry = 0;
while(retry++ < CONNECTION_RETRIES){
ps.executeUpdate(sqlQuery);
break;
}
if(retry < CONNECTION_RETRIES)wasExecuted=true; return wasExecuted;
} /**
* ResultSet runChainedQuery()
* Executes a chained mode transaction query.
*
* @param <b>String</b> containing a SQL statement
* @param <b>String</b> containing the isolation level to run the transaction.
* @return ResultSet
*/
public ResultSet runChainedQuery( String sqlQuery, String isolationLevel )
throws Exception { int retry = 0; //Create the resultset and statement object.
ResultSet resultSet = null;
Statement dbStatement = null;
// Connect to the database.
dbStatement = dbCon.createStatement();
// Retry the query until complete or timeout.
while (retry++ < QUERY_RETRIES) {
// Begin a transaction.
dbStatement.executeUpdate( "Begin Transaction" );
// Set the isolation level.
dbStatement.executeUpdate( new String( "Set Transaction Isolation level " + isolationLevel ) );
// Execute the query.
resultSet = dbStatement.executeQuery( sqlQuery );
// Commit the transaction.
dbStatement.executeUpdate( "commit" );
// Close the connection.
dbStatement.close();
break;
}
return resultSet;
} /**
* boolean runChainedUpdate()
* Executes a chained mode transaction query.
*
* @param String[] containing a series of SQL statments
* @param String containing the isolation level to run the transaction.
* @return boolean
*/
public boolean runChainedUpdate( String [] sqlQuery, String isolationLevel )
throws Exception {
int retry = 0; // Create the statement object.
Statement dbStatement = null;
boolean wasExecuted = false;
// Connect to the database.
dbStatement = dbCon.createStatement(); while (retry++ < QUERY_RETRIES) {
// Begin a new transaction.
try {
dbStatement.executeUpdate( "Begin Transaction" );
// Set the isolation level.
dbStatement.executeUpdate( new String( "Set Transaction Isolation level " + isolationLevel ) );
// For each sql statement, perform the update.
for( int i=0; i<sqlQuery.length; i++ ) {
dbStatement.executeUpdate( sqlQuery[i] );
}
// Commit the transaction and close.
dbStatement.executeUpdate( "commit" );
dbStatement.close();
wasExecuted = true;
} catch (Exception e) {
errorString = new String( "Error executing: " + sqlQuery + "\nCause: " + e.toString() );
hasError = true;
// Rollback if an error has occured.
dbStatement.executeUpdate( "rollback" );
dbStatement.close();
}
}
return wasExecuted;
}
}

4. 测试代码

import java.sql.*;

public class DBConnectionTest {
public static void main(String[] args) {
/*
* if(args.length < 3){
* System.out.println("Syntax:DBConnection [url][username][password]");
* //url = jdbc:postgresql:database or
* jdbc:postgresql://host:port/database System.exit(-1); }
*/ String url = "jdbc:postgresql://localhost:5432/postgres";
String username = "postgres";
String password = "741613551";
String sql = "select sName from student";
String s; try {
System.out.println("Step 01: Registering JDBC Driver"); /* There are three ways to registe driver. */
// write your code here for Registering JDBC Driver
// 先注册JDBC驱动 org.postgresql.Driver
Class.forName("org.postgresql.Driver");
System.out.println("Step 02: Establishing connection to: \n\t"
+ url); // write your code here to get a connection
// url = jdbc:postgresql:database or
// jdbc:postgresql://host:port/database
Connection conn = DriverManager.getConnection(url, username,
password);
System.out.println("Step 03: Creating SQL statement."); // write your code here to create a SQL statement
Statement state = conn.createStatement();
System.out.println("Step 04: Executing SQL statement."); // write your code here to execute your SQL statement and recieve
// the result
ResultSet resultSet = state.executeQuery(sql);
System.out.println("Step 05: Printing result."); // write your code here to print the result
while (resultSet.next()) {
System.out.println(resultSet.getString("sName"));
}
System.out.println("Step 06: Closing JDBC objects."); // write your code here to close all JDBC objects. resultSet.close();
state.close();
conn.close();
System.out.println("End.");
} catch (Exception e) {
System.out.println(e);
}
}
}

5. JDBC教程:http://www.yiibai.com/jdbc/jdbc-introduction.html

postgreSQL连接 java接口的更多相关文章

  1. java接口调用——webservice就是一个RPC而已

    很多新手一听到接口就蒙逼,不知道接口是什么!其实接口就是RPC,通过远程访问别的程序提供的方法,然后获得该方法执行的接口,而不需要在本地执行该方法.就是本地方法调用的升级版而已,我明天会上一篇如何通过 ...

  2. python面向对象进阶 反射 单例模式 以及python实现类似java接口功能

    本篇将详细介绍Python 类的成员.成员修饰符.类的特殊成员. 类的成员 类的成员可以分为三大类:字段.方法和特性. 注:所有成员中,只有普通字段的内容保存对象中,即:根据此类创建了多少对象,在内存 ...

  3. OpenCV4Android开发之旅(一)----OpenCV2.4简介及 app通过Java接口调用OpenCV的示例

    转自:  http://blog.csdn.net/yanzi1225627/article/details/16917961 开发环境:windows+ADT Bundle+CDT+OpenCV-2 ...

  4. 十分钟搭建redis单机版 & java接口调用

    本次单机版redis服务器搭建采用的包为redis-3.0.0.tar.gz,主要是记录下安装的心得,不喜勿喷! 一.搭建redis服务器单机版 1.上传redis-3.0.0.tar.gz到服务器上 ...

  5. Apache Solr 初级教程(介绍、安装部署、Java接口、中文分词)

    Python爬虫视频教程零基础小白到scrapy爬虫高手-轻松入门 https://item.taobao.com/item.htm?spm=a1z38n.10677092.0.0.482434a6E ...

  6. 使用swig将C/C++代码转为JAVA接口(Windows平台)

    小弟一直没用过Linux. 平时的码也只是在WINDOW上用SWIG或CYGWIN进行编译. 下面的例子,先从网上找来一个.c文件. example.c /* File : example.c */ ...

  7. Java-Runoob-面向对象:Java 接口

    ylbtech-Java-Runoob-面向对象:Java 接口 1.返回顶部 1. Java 接口 接口(英文:Interface),在JAVA编程语言中是一个抽象类型,是抽象方法的集合,接口通常以 ...

  8. jmeter使用BeanShell Sampler测试自己写的java接口(一)

    上次直接使用jmeter里面的FTPsampler没有连接成功 现在想着自己写java代码,通过jmeter进行调用进行连接测试实现并发 代码引文: http://www.cnblogs.com/ch ...

  9. Java接口对Hadoop集群的操作

    Java接口对Hadoop集群的操作 首先要有一个配置好的Hadoop集群 这里是我在SSM框架搭建的项目的测试类中实现的 一.windows下配置环境变量 下载文件并解压到C盘或者其他目录. 链接: ...

随机推荐

  1. Json转换工具类(基于google的Gson和阿里的fastjson)

    在项目之中我们经常会涉及到字符串和各种对象的转换,为此特地整理了一下常用的转换方法 一.基于com.google.code.gson封装的json转换工具类 1. 在pom.xml文件里面引入gson ...

  2. ubuntu 系统启动异常之无登录界面和版本号启动四个点的地方卡住

    zlib 搞的鬼,还没结局,由于rtmpdump 安装需要安装独立zlib库,装完后重启,完了吓一跳,卡住,尼玛这一年的代码都在里面啊!!! ldd /usr/sbin/python 查询库依赖zli ...

  3. (转)Android 5.1.1 源码目录结构

    转自:http://blog.csdn.net/tfslovexizi/article/details/51888458最近公司培训新同事,我负责整理一点关于android的基础知识,遥想当年,刚接触 ...

  4. [2013.7.5新鲜出炉] Ubuntu12.04下载Android4.0.1源码全过程----------------折腾两天,终于下好,附若干问题解决

    本文转至 http://blog.csdn.net/yanzi1225627/article/details/9255457 下载源码这一步折腾了我整整两天,期间遇到很多问题,哎,记录于此,希望日后再 ...

  5. Python——signal

    该模块为在Python中使用信号处理句柄提供支持.下面是一些使用信号和他们的句柄时需要注意的事项: 除了信号 SIGCHLD 的句柄遵从底层的实现外,专门针对一个信号的句柄一旦设置,除非被明确地重置, ...

  6. 升级win10,提示(RAM)内存不足2G的解决的方法,亲測可行

    前两天升级win10,检測我内存不足2G,可我的电脑是8G的内存如图 百度,google了非常多方法,有些是两根内存,去掉一个就好了,但是我的就一根8G的,其它就没什么好的方法了,改biosCPU选项 ...

  7. DWZ主从表界面唯一性验证(自写js)(二)

    上篇介绍了自写js判断的前三项,本篇博客介绍第四步,关于触发课程代码文本框的离开事件后,判断一整列的课程代码之间是否有重复的值. 此问题可以提取为判断一个数组里是否有重复值,重复值是什么. 第四步→判 ...

  8. Hopewell Project Sharing项目总结分享PPT

    这篇随笔记录的是2013年底,Hopewell Project已经成功验收后,开项目分享会所编写的PPT. 由于此项目是本人带领Team成员一起开发,而且关键技术是自己把控,所以公司希望能开个项目分享 ...

  9. 安装MySQL-python: EnvironmentError:mysql config not found

    1执行 sudo yum install python-devel 2 find / -name mysql_config 在/usr/bin/下发现了这个文件 3. 后修改MySQL-python- ...

  10. PyCharm搭建pyqt5开发环境

    PyCharm搭建PyQt5开发环境 1.安装PyQt5 2.PyCharm环境配置 2.1 添加QtDesigner 2.2 添加PyUIC 2.3 添加Pyrcc 2.4 添加assistant ...