java链接pgsql代码
时间: 2023-12-17 09:03:35 浏览: 111
以下是Java连接PostgreSQL数据库的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PostgreSQLJDBC {
public static void main(String args[]) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/testdb",
"username", "password");
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, age FROM mytable;");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("ID = " + id);
System.out.println("NAME = " + name);
System.out.println("AGE = " + age);
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
```
请注意,您需要将代码中的 "testdb"、"username" 和 "password" 替换为您自己的数据库名称、用户名和密码。另外,您需要确保已经在项目中引入了 PostgreSQL 驱动程序。
阅读全文