目录
- 前置准备
- 代码
前置准备
因为连接PostgreSQL需要先安装PG,所以以下给出PG的简单安装教程:
window安装PostgreSQL
对应的建表语句:
DROP TABLE IF EXISTS student;
CREATE TABLE student (
id serial NOT NULL,
name varchar(100) NOT NULL,
sex varchar(5) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO student (id, name, sex) VALUES (1, '小明', '男');
INSERT INTO student (id, name, sex) VALUES (2, '小红', '女');
CREATE TABLE IF NOT EXISTS score
(
id integer NOT NULL,
student_id integer NOT NULL,
grade integer NOT NULL,
PRIMARY KEY (id)
);
insert into score(id,student_id,grade)values(1,1,80);
insert into score(id,student_id,grade)values(2,2,90);
关于PG如何建表:
PostgreSQL表的创建
代码
下面是连接JDBC并进行查询的代码,注意几个参数:
- org.postgresql.Driver,该参数需要jar包,通过maven配置更加简单。
- jdbc:postgresql://localhost:5432/School,连接的本地postgreSQL,School是数据库名称
- user和passwd自然不用说,配置PG的时候自然会设置,默认user为postgres
import java.sql.*;
public class PostgreSQLJDBC {
public static void main( String args[] ) {
Connection conn = null;
Statement stmt = null;
try {
// 加载 PostgreSQL 驱动类
Class.forName("org.postgresql.Driver");
// 创建数据库连接
String url = "jdbc:postgresql://localhost:5432/School";
String user = "postgres";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
// 创建 Statement 对象
stmt = conn.createStatement();
// 执行查询语句
String sql = "SELECT * FROM student";
ResultSet rs = stmt.executeQuery(sql);
// 处理查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String sex = rs.getString("sex");
System.out.println(id + "\t" + name + "\t" + sex);
}
// 关闭 ResultSet、Statement 和 Connection 对象
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
// 处理 JDBC 异常
se.printStackTrace();
} catch(Exception e) {
// 处理 Class.forName 异常
e.printStackTrace();
} finally {
// 关闭资源
try {
if(stmt!=null) stmt.close();
} catch(SQLException se2) {
}
try {
if(conn!=null) conn.close();
} catch(SQLException se3) {
se3.printStackTrace();
}
}
}
}
pom.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mvn_calcite_test</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.calcite</groupId>
<artifactId>calcite-core</artifactId>
<version>1.19.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.2</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.18</version>
</dependency>
</dependencies>
</project>
只需要配置maven和上述代码,就轻松实现了Java使用JDBC连接PostgreSQL。