java - 在 intellij 中使用 java 连接到数据库(postgres)
问题描述
我想编写一个代码来从输入中获取我的查询并运行它并向我显示结果。我必须在我的代码中连接到数据库。我通过 intellij 数据库扩展连接到 postgres,我的查询在控制台中运行。
但我想在我的代码中做到这一点(我的意思是从用户那里获取查询并运行它)。是否可以使用此数据库连接并对其运行查询?
我也通过此代码成功连接:
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/db","postgres", "pass");
我写了一些查询。所有查询类型(例如update
, delete
, insert
, ...)都运行并且结果在中可见pgadmin
但我希望在我的 java 代码中得到结果
解决方案
这是一个使用 JDBC 运行查询的示例。您可以在此处下载 JDBC https://jdbc.postgresql.org/download.html并添加到您的类路径中
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PostgreSqlExample {
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/example", "postgres", "postgres")) {
System.out.println("Java JDBC PostgreSQL Example");
System.out.println("Connected to PostgreSQL database!");
Statement statement = connection.createStatement();
System.out.println("Reading car records...");
System.out.printf("%-30.30s %-30.30s%n", "Model", "Price");
ResultSet resultSet = statement.executeQuery("SELECT * FROM public.cars");
while (resultSet.next()) {
System.out.printf("%-30.30s %-30.30s%n", resultSet.getString("model"), resultSet.getString("price"));
}
} /*catch (ClassNotFoundException e) {
System.out.println("PostgreSQL JDBC driver not found.");
e.printStackTrace();
}*/ catch (SQLException e) {
System.out.println("Connection failure.");
e.printStackTrace();
}
}
}
推荐阅读
- ionic-framework - '@ionic/storage-angular',数据在刷新后被删除
- jupyter-lab - ModuleNotFoundError: 没有实验室扩展。当终端中的 exec “jupyter labextension develop .--overwrite”
- laravel - Laravel - Eloquent 如何建立这种关系 HasMany -> BelongToThrough
- r - 在统计中使用 set.seed()
- angular - FormArray,用于角度单元测试的表单控件(茉莉花)
- javascript - ionic vue 无法从资产文件夹中选择图像?
- reactjs - 如何使用 React 路由器在兄弟组件之间共享数据(道具或其他方式)
- openbmc - OpenBMC WebUI 更新版本 MANIFEST 和 publickey
- c - 在 C 中实现按位运算
- java - 在 Java 中使用正则表达式替换第 n 个字符