JAVA链接postgresql的jdbc
时间: 2023-09-28 09:11:23 浏览: 50
1. 下载并安装postgresql数据库,创建一个新的数据库。
2. 下载postgresql的JDBC驱动程序(postgresql.jdbc.Driver)。
3. 将驱动程序添加到您的Java项目中。您可以将JDBC驱动程序直接放在项目中,也可以将其放在系统类路径中。
4. 通过以下代码建立数据库连接:
```java
import java.sql.*;
public class DBConnection {
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost/mydatabase";
// 数据库的用户名和密码
static final String USER = "postgres";
static final String PASS = "mypassword";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行查询
System.out.println("实例化Statement对象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, age FROM Students";
ResultSet rs = stmt.executeQuery(sql);
// 展开结果集数据库
while(rs.next()){
// 通过字段检索
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 姓名: " + name);
System.out.print(", 年龄: " + age);
System.out.println();
}
// 完成后关闭
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 se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
```
5. 运行代码,如果一切正常,您应该能够连接到postgresql数据库并从表中检索数据。