MySQL Netbeans Java 结果集失败
Posted
技术标签:
【中文标题】MySQL Netbeans Java 结果集失败【英文标题】:MySQL Netbeans Java ResultSet Failure 【发布时间】:2015-08-05 04:35:44 【问题描述】:您好,我在 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);
【问题讨论】:
【参考方案1】: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);
【讨论】:
参考:MySQLVERSION()
function https://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_version以上是关于MySQL Netbeans Java 结果集失败的主要内容,如果未能解决你的问题,请参考以下文章
Tesseract 加载语言失败 (Tess4j / Java / Netbeans)