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(); } }
最新文章
- 初学HTML 常见的标签(二) 列表标签
- js 事件绑定
- LinkedHashMap源码详解
- OC基础--block
- 使用visual studio 2012 编译opencv2.4.9
- C#之重定向输入输出
- 管理Undo数据
- Python之路Day16
- Redis 安装与简单示例(转)
- Linq to Sql:N层应用中的查询(上) : 返回自定义实体
- DES加密And解密
- C# 判断网站是否能访问或者断链
- selenium-01 搭建环境
- ffdshow 源代码分析 7: libavcodec视频解码器类(TvideoCodecLibavcodec)
- 前端开发之css
- Windows PowerShell 入門(5)-制御構文
- vue-cli 使用Mint-UI
- Oracle查询锁表和解锁
- [BZOJ1196][HNOI2006]公路修建问题 二分答案+最小生成树
- 转【非容器化Jenkins连接Kubernetes】
热门文章
- 【20.35%】【codeforces 651D】Image Preview
- ES数据
- java开发环境配置(windows下JDK7+tomcat7)
- BS_OWNERDRAW风格的作用和例子(值得研究,待续)
- 黑科技 —— Type-C 接口与 USB3.1
- ios中 微信点击 某个元素 该元素会闪一下
- TCP/IP之封装,分用,server模型
- 【转】mysql的SQL_NO_CACHE(在查询时不使用缓存)和sql_cache用法
- SQL语句中使用Group by
- Matlab Tricks(十八)—— 矩阵间元素距离的计算