【问题标题】:connecting to database(postgres) with java in intellij在 intellij 中使用 java 连接到数据库(postgres)
【发布时间】:2019-12-27 09:14:42
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: java sql postgresql jdbc


    【解决方案1】:

    这是一个使用 JDBC 运行查询的示例。你可以在这里https://jdbc.postgresql.org/download.html 下载 JDBC 并添加到你的类路径中

    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();
            }
        }
    }
    

    【讨论】:

    • 这样我们必须为每个表编写相同的代码,但我想得到一个表作为结果
    • 纯jdbc就是这样,你可以使用库来重构所有这些代码,比如Hibernate、JOOQ
    猜你喜欢
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 2012-08-21
    相关资源
    最近更新 更多