首页 > 解决方案 > 在 intellij 中使用 java 连接到数据库(postgres)

问题描述

我想编写一个代码来从输入中获取我的查询并运行它并向我显示结果。我必须在我的代码中连接到数据库。我通过 intellij 数据库扩展连接到 postgres,我的查询在控制台中运行。

我的情况

但我想在我的代码中做到这一点(我的意思是从用户那里获取查询并运行它)。是否可以使用此数据库连接并对其运行查询?

我也通过此代码成功连接:

Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/db","postgres", "pass");

我写了一些查询。所有查询类型(例如update, delete, insert, ...)都运行并且结果在中可见pgadmin但我希望在我的 java 代码中得到结果

标签: javasqlpostgresqljdbc

解决方案


这是一个使用 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();
        }
    }
}

推荐阅读