【问题标题】:error with instantiating a SQL statement (Java) (JDBC)实例化 SQL 语句 (Java) (JDBC) 时出错
【发布时间】:2013-02-27 16:22:11
【问题描述】:

我一直在尝试在 netbeans 中练习使用 JDBC,但遇到了一个小问题,现在我加载了驱动程序,建立了与 SQL 的连接,但由于某种原因,我的 SQL 语句不起作用,我会的如果有人能忍受我很高兴

public void dbTest() {
    try {
        Class.forName(
                "com.mysql.jdbc.Driver").newInstance();
    } catch (InstantiationException |
            IllegalAccessException |
            ClassNotFoundException e) {
    }

    try (Connection connection = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/", "root", "explore");
            Statement statement = (Statement) connection.createStatement()) {
        String query = "select first_name, last_name"
                + " from sakila.customer "
                + "where address_id < 10";
        try (ResultSet resultset =
                statement.executeQuery(query)) {
            while (resultset.next()) {
                String firstName =
                        resultset.getString("first_name");
                String lastName =
                        resultset.getString("last_name");
                System.out.println(firstName + " " + lastName);
            }
        }
    } catch (SQLException e) {
    }
}

这行代码给我带来了麻烦

Statement statement = (Statement) connection.createStatement()

谢谢!!

【问题讨论】:

  • 当你说它给你带来麻烦时,你是什么意思?它抛出异常?它不会让你编译?
  • 很可能您没有使用java.sql.Statement。你可能正在使用'java.beans.Statement'
  • @KevinD 它不会让我编译
  • @PremGenError 我正在使用java.beans.Statement,但它会有什么不同呢?
  • 你应该使用java.sql.Statement通过JDBC执行查询

标签: java sql netbeans jdbc


【解决方案1】:

正如大多数 cmets 所述,您应该使用 java.sql.Statement 而不是 java.beans.Statement

我注意到您的代码的另一件事是您正在查询并且您没有指定应该从哪个数据库执行这些操作,这将引导您到SQLException。因此,您必须再次将 url 字符串从 "jdbc:mysql://localhost:3306/" 更改为 "jdbc:mysql://localhost:3306/database_name"

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    相关资源
    最近更新 更多