gpt4 book ai didi

java - MySQL Netbeans Java 结果集失败

转载 作者:行者123 更新时间:2023-11-29 06:26:59 24 4
gpt4 key购买 nike

您好,我在 Netbeans 中安装了 MySql,并且一直在尝试将 Java 与 MySQL 结合使用,但是在运行它时遇到了问题。我的数据库称为“测试”,我的表是“任务”。我拥有的两列是:“id”和“task”(我意识到将变量命名为与表相同的名称可能不是一个好主意)。我在代码区域也有一个附带问题,询问它的作用。这是错误:运行:

May 22, 2015 11:52:25 PM databasetest.DatabaseTest main
SEVERE: Operation not allowed after ResultSet closed
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:804)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6986)
at databasetest.DatabaseTest.main(DatabaseTest.java:43)

BUILD SUCCESSFUL (total time: 41 seconds)

这是我的代码:

package databasetest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DatabaseTest {

public static void main(String[] args) {

Connection con = null;
Statement st = null;
ResultSet rs = null;
PreparedStatement pst = null;

String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "cinder";

try {

String author = "Trygve Gulbranssen";

con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
//^^ what is VERSION? What is this supposed to be doing?

for (int i=1; i<=1000; i++) {
String query;
query = "INSERT INTO task(task) VALUES(" + 2*i + ")";
st.executeUpdate(query);
}

if (rs.next()) {
System.out.println(rs.getString(1));
}

} catch (SQLException ex) {
Logger lgr = Logger.getLogger(DatabaseTest.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);

} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}

} catch (SQLException ex) {
Logger lgr = Logger.getLogger(DatabaseTest.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}

最佳答案

SELECT VERSION() 旨在告诉您您的 MySQL 版本。首先,打印 SELECT 的结果,然后运行其他查询。使用 Statement 运行中间插入查询会隐式关闭 ResultSet,因此会出现错误。移动

if (rs.next()) {
System.out.println(rs.getString(1));
}

运行前

for (int i=1; i<=1000; i++) {
// String query;
String query = "INSERT INTO task(task) VALUES(" + 2*i + ")";
st.executeUpdate(query);
}

关于java - MySQL Netbeans Java 结果集失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30408811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com