postgresql + JDBC 学习
Based on debian 9, postgresql 9.6 and Java 8, at Dec-24-2018
=================================================
1. Debain Install
=================================================
* Install DB and JDBC
sudo aptitude install postgresql libpostgresql-jdbc-java
--below will be installed
default-jdk-doc{a} libpostgresql-jdbc-java libpostgresql-jdbc-java-doc openjdk-8-doc{a} postgresql-9.6
* Configure
1. re-configure listner
sudo vim /etc/postgresql/9.6/main/postgresql.conf
listen_addresses = '*' # what IP address(es) to listen on;
2. stop / start / status
The service: /lib/systemd/system/postgresql.service
sudo systemctl stop/start postgresql.service
* Reference
[PostgreSQL Java tutorial](http://www.postgresqltutorial.com/postgresql-jdbc/)
=================================================
2. create user / db /table /data
=================================================
* create db user / database / table and grant privi
sudo passwd postgresql
create user dbuser with password 'dbuser';
create database exampledb with owner dbuser;
grant all privileges on database exampledb to dbuser;
* Login and manage data
psql -U dbuser -d exampledb -h 127.0.0.1 -p 5432
CREATE TABLE emp(name VARCHAR(20), id integer, signup_date DATE);
插入数据
INSERT INTO emp(name, id, signup_date) VALUES('cliff',1,'2011-12-22');
INSERT INTO emp(name, id, signup_date) VALUES('jim',2,'2012-12-22');
INSERT INTO emp(name, id, signup_date) VALUES('andy',3,'2013-12-22');
INSERT INTO emp(name, id, signup_date) VALUES('wind',4,'2014-12-22');
alter table emp add column resume bytea;
=================================================
2. A Query to get column name automatically AND multiple parameters in IN cluase
=================================================
* Demo connection build / close
* Demo SQL query - ResultSetMetaData usage and pass multiple values to IN (?)
* Demo byteA/blob update
* Demo byteA/blob read
import java.io.*;
import java.sql.*;
public class FirstDemo { private Connection conn=null; /*
* get connection
*/
public void getConn(){ String url="jdbc:postgresql://localhost/exampledb", user="dbuser", password="dbuser"; try {
conn=DriverManager.getConnection(url, user, password);
System.out.println("The connection build as "+conn.getSchema());
} catch (SQLException e) {
System.out.println(e.getErrorCode() + e.getSQLState() + e.getMessage());
e.printStackTrace();
}
} /*
* get connection
*/
public void CloseConn(){
try {
conn.close();
} catch (SQLException e) {
System.out.println(e.getErrorCode() + e.getSQLState() + e.getMessage());
e.printStackTrace();
}
} /*
* Run a query and return the result
* 1. get the column name from ResultSetMetaData
* 2. use "nest" to pass multiple parameters to in ( ? )
*/
public void query(){
System.out.println("Query starting :");
Integer[] ids={1,2,3};
try {
PreparedStatement pst=conn.prepareStatement("select * from emp where id in (SELECT * FROM unnest(?))");
//pst.setInt(1, 1);
//pst.setInt(2, 2);
//pst.setInt(3, 3);
Array a = conn.createArrayOf("integer", ids);
pst.setArray(1, a);
ResultSet rs=pst.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.printf("%-20s%-20s\n", rsmd.getColumnName(1), rsmd.getColumnName(2)); while(rs.next()) { System.out.printf("%-20s%-20d\n", rs.getString(1), rs.getInt(2)); }
pst.close(); } catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{ } } /*
* Run a query and return the result
* byteA / blob read
*/
public void byteARead(){
System.out.println("byteA reading :");
File f;
FileOutputStream fos;
byte[] b = null;
PreparedStatement pst;
try { f = new File("/home/ftian/postgresqlCliffReadme.txt");
fos = new FileOutputStream (f); pst=conn.prepareStatement("select resume from emp where id =1");
ResultSet rs=pst.executeQuery();
while(rs.next()) { b = rs.getBytes(1); }
fos.write(b);
fos.close();
pst.close();
System.out.println("byteA reading done"); } catch (Exception e) {
e.printStackTrace();
}
} /*
* Run a query and return the result
* byteA / blob insert
*/
public void byteAInsert(){
System.out.println("byteA inserting :");
File f;
FileInputStream fis;
PreparedStatement pst;
try { f = new File("/home/ftian/workspace/postgres/postgresqlCliffReadme.txt");
fis = new FileInputStream (f); pst=conn.prepareStatement("update emp set resume=? where id =?");
pst.setBinaryStream(1, fis, (int)f.length());
pst.setInt(2, 1);
pst.executeUpdate();
System.out.println("byteA inserting done "+pst.getUpdateCount());
fis.close();
pst.close(); } catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) { FirstDemo fd = new FirstDemo();
fd.getConn();
fd.query();
fd.byteAInsert();
fd.byteARead();
fd.CloseConn(); } }
postgresql + JDBC 学习的更多相关文章
- JDBC学习笔记(2)——Statement和ResultSet
Statement执行更新操作 Statement:Statement 是 Java 执行数据库操作的一个重要方法,用于在已经建立数据库连接的基础上,向数据库发送要执行的SQL语句.Statement ...
- JDBC学习笔记(1)——JDBC概述
JDBC JDBC API是一个Java API,可以访问任何类型表列数据,特别是存储在关系数据库中的数据.JDBC代表Java数据库连接. JDBC库中所包含的API任务通常与数据库使用: 连接到数 ...
- 【转】JDBC学习笔记(2)——Statement和ResultSet
转自:http://www.cnblogs.com/ysw-go/ Statement执行更新操作 Statement:Statement 是 Java 执行数据库操作的一个重要方法,用于在已经建立数 ...
- 【转】JDBC学习笔记(1)——JDBC概述
转自:http://www.cnblogs.com/ysw-go/ JDBC JDBC API是一个Java API,可以访问任何类型表列数据,特别是存储在关系数据库中的数据.JDBC代表Java数据 ...
- jdbc学习总结
jdbc学习总结: 一.简介: jdbc,直译为java连接数据库.实际为java为很好的操作数据库而提供的一套接口,接口的实现(即驱动)由各个数据库厂商提供. 二.知识要点: 连接5要素,3 ...
- JDBC 学习笔记(十一)—— JDBC 的事务支持
1. 事务 在关系型数据库中,有一个很重要的概念,叫做事务(Transaction).它具有 ACID 四个特性: A(Atomicity):原子性,一个事务是一个不可分割的工作单位,事务中包括的诸操 ...
- JDBC 学习笔记(十)—— 使用 JDBC 搭建一个简易的 ORM 框架
1. 数据映射 当我们获取到 ResultSet 之后,显然这个不是我们想要的数据结构. 数据库中的每一个表,在 Java 代码中,一定会有一个类与之对应,例如: package com.gerrar ...
- JDBC 学习笔记(六)—— PreparedStatement
1. 引入 PreparedStatement PreparedStatement 通过 Connection.createPreparedStatement(String sql) 方法创建,主要用 ...
- JDBC学习笔记二
JDBC学习笔记二 4.execute()方法执行SQL语句 execute几乎可以执行任何SQL语句,当execute执行过SQL语句之后会返回一个布尔类型的值,代表是否返回了ResultSet对象 ...
随机推荐
- 前端自动化之路之gulp,node.js
随着现在前端技术的不断发展,和各个公司对前端项目开发更新速度的要求,前端自动化越来越受到大家的重视,之前传统的前端开发方式已经越来越不能满足开发的需求了,于是各种自动化工具随之产生了.而gulp就是其 ...
- 不要放弃使用border-box
不知道有多少老前端像我这样,在项目中很少使用box-sizing这个属性值.因为CSS2.1中只有content-box这一种盒子模式,在CSS3还没有流行的时候,大家在工作中大量基于这种盒子模式写C ...
- linux下jar包的生存与开机自动启动
前言 作为一名Android开发,有的时候也是要做做其他工作的,前段时间写了一个很简单的java消息转发程序,因为和三方厂商合作,对方只提供了java的sdk,然而我们这边都是清一色的C#后台开发人员 ...
- 【27.34%】【codeforces 611D】New Year and Ancient Prophecy
time limit per test2.5 seconds memory limit per test512 megabytes inputstandard input outputstandard ...
- 获取全局上下文(getApplicationContext)_创建Shared Preference工具类_实现自动登录
获取全局上下文(getApplicationContext)_创建Shared Preference工具类_实现自动登录 ===========================获取全局上下文(getA ...
- Ubuntu 16.04安装MinGW32(在/etc/apt/sources.list里添加源)
Ubuntu 16.04下直接使用命令安装MinGW32: sudo apt-get install mingw32 但是,会报错: Unable to locate package mingw3 ...
- javascript对象属性为空的判断
zepto: $.isEmptyObject = function(obj) { var name for (name in obj) return false return true } $.isE ...
- message contains no documents code:13066 mongdb数据库报的错误
message contains no documents code:13066stackoverflow上面的回答是: What version of the C# driver are you ...
- 深刻认识OpenStack
OpenStack 1 OpenStack简单介绍 Openstack archite ...
- APP和服务端-架构设计(二)
1. App架构设计经验谈:接口的设计 App与服务器的通信接口如何设计得好,需要考虑的地方挺多的,在此根据我的一些经验做一些总结分享,旨在抛砖引玉. 1.1 安全机制的设计 现在,大部分App的接口 ...