java执行pgsql语句的方法
时间: 2023-11-21 09:09:41 浏览: 243
在Java中执行PostgreSQL语句,有多种方式可以实现,下面介绍两种常用的方法:
1. 使用JDBC连接数据库并执行SQL语句
首先需要在项目中引入PostgreSQL JDBC驱动,然后通过JDBC连接数据库,执行SQL语句。示例代码如下:
```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");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "SELECT * FROM mytable;";
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.println("ID = " + id);
System.out.println("NAME = " + name);
System.out.println("AGE = " + age);
}
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");
}
}
```
2. 使用Spring JDBC Template
Spring JDBC Template是Spring框架中提供的一种简化JDBC操作的方式,可以方便地执行SQL语句,并且不用手动释放资源。示例代码如下:
```java
import org.springframework.jdbc.core.JdbcTemplate;
public class PostgreSQLJDBC {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void executeSql() {
String sql = "SELECT * FROM mytable;";
jdbcTemplate.query(sql, new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
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);
}
});
}
}
```
以上是两种常用的在Java中执行PostgreSQL语句的方法。
阅读全文