java - 在 Java 程序中开始结果集之前获取 SQL 错误 1078

标签 java mysql resultset

<分区>

我有一个 Java 方法,它应该从一个 MySQL 行中获取列值并创建一个包含这些值的字符串。运行时,它会生成 SQL 错误 1078“结果集开始前。”

这是发生错误的类(问题出在 listPosesInSection 方法中:

/** Class used to access the database */

import java.sql.*;
import java.util.ArrayList;

import javax.swing.JOptionPane;

public class YogaDatabaseAccess {
String dbUrl = "jdbc:mysql://localhost/yoga";
private Connection connection;
private ResultSet rset;
private ResultSetMetaData rsMetaData;
private Statement statement;
private PreparedStatement pStatementAll = null;
private PreparedStatement pStatementPartial = null;

// Strings for queries and updates
String strListPosesNotPrimary;
String strInsertNewClass;
String strInsertNewSection;
String strInsertNewPose;
String strUpdateClass;
String strUpdateSection;
String strUpdatePose;
String strArrangePoseOrder;

private String[] poseArray;

// Constructor
YogaDatabaseAccess() {
    connectToDatabase();
}

// Method that connects to database
private void connectToDatabase() {
    try {
        connection = DriverManager.getConnection(dbUrl, "Kyle", "Kullerstrand@2");
        System.out.println("Database connected");
    }
    catch(SQLException e) {
        System.out.println(e.getMessage());
    }
}

// Query that returns lists to be used with combo boxes
public String listForBoxes(String listName) {
    // List to be returned
    String strList = "";

    // Determine name of the database table for this list
    String listTableName;
    if (listName == "pose")
        listTableName = listName + "s";
    else if (listName == "class")
        listTableName = listName + "es";
    else
        listTableName = listName;

    // Determine the database column name for this list
    String listColumnName = listName + "_name";

    // Run the query
    try {
        statement = connection.createStatement();
        rset = statement.executeQuery("SELECT DISTINCT " + listColumnName + " FROM " + listTableName +
                " ORDER BY " + listColumnName);
        while (rset.next()){
            strList = strList + rset.getString(listColumnName) + ", ";
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return strList;
}

// Query that returns list of primary poses for a section
public String listPrimaryPoses(String sectionName) {
    // List to be returned
    String strList = "";

    // Run the query
    try {
        statement = connection.createStatement();
        rset = statement.executeQuery("SELECT DISTINCT pose_name FROM poses WHERE primarily_suitable_for = '" + sectionName + 
                "' OR primarily_suitable_for = 'Anything' ORDER BY pose_name");
        while (rset.next()){
            strList = strList + rset.getString("pose_name") + ", ";
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return strList;
}

// Query that returns list of secondary poses for a section
public String listSecondaryPoses(String sectionName) {
    // List to be returned
    String strList = "";

    // Run the query
    try {
        statement = connection.createStatement();
        rset = statement.executeQuery("SELECT DISTINCT pose_name FROM poses WHERE sometimes_suitable_for = '" + sectionName + "' ORDER BY pose_name");
        while (rset.next()){
            strList = strList + rset.getString("pose_name") + ", ";
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return strList;
}

// Query that returns the poses within a specific section
public String listPosesInSection(String tableName, String sectionName) {
    String strList;
    StringBuilder strBuilderList  = new StringBuilder("");
    // Run the query
    try {
        statement = connection.createStatement();
        // Query will collect all columns from one specific row
        rset = statement.executeQuery("SELECT * FROM " + tableName + " WHERE " + tableName + "_name = '" + sectionName + "'");
        while (rset.next()) {
            for (int i = 2; i <= countColumnsInTable(tableName); i++) // First value (0) is always null, skip section name (1)
                if (rset.getString(i) != null) // If column has a value
                    strBuilderList.append(rset.getString(i) + "\n");
        } 
    } catch (SQLException e) {
        e.printStackTrace();
    }
    strList = strBuilderList.toString();
    return strList.replaceAll(", $",""); // Strips off the trailing comma
}

// Insert statement that inserts a new class into the classes table
public void insertNewClass(String className) {
    /** String insert = "INSERT INTO poses (pose_name, primarily_suitable_for, sometimes_suitable_for) values(?, ?, ?)";
    System.out.println("About to create the prepared statement");
    // Run the insert
    try {
        pStatement = connection.prepareStatement(insert);
        // statement.execute("INSERT IGNORE INTO poses VALUES ('" + poseName + "', '" + suitableFor + "', '" + suitableForSometimes + "')");
        pStatement.setString(1, poseName);
        pStatement.setString(2, suitableFor);
        pStatement.setString(3, suitableForSometimes);

        System.out.println("Created the prepared statement");

          // execute query, and return number of rows created
        pStatement.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    } */
}

// Insert statement that inserts a new pose into poses table
public void insertNewPose(String poseName, String suitableFor, String suitableForSometimes) {
    String insertAll = "INSERT INTO poses (pose_name, primarily_suitable_for, sometimes_suitable_for) values(?, ?, ?)";
    String insertPartial = "INSERT INTO poses (pose_name, primarily_suitable_for) values(?, ?)";
    // Run the insert
    try {
        if (suitableForSometimes == "NULL") {  // Insert statement contains a null value for sometimes suitable column
            pStatementPartial = connection.prepareStatement(insertPartial);
            pStatementPartial.setString(1, poseName);
            pStatementPartial.setString(2, suitableFor);
            pStatementPartial.executeUpdate();
        } else {  // Insert statement contains values for all three columns
            pStatementAll = connection.prepareStatement(insertAll);
            pStatementAll.setString(1, poseName);
            pStatementAll.setString(2, suitableFor);
            pStatementAll.setString(3, suitableForSometimes);
            pStatementAll.executeUpdate();
        }
    } catch (SQLException e) {
        System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
        JOptionPane.showMessageDialog(null, "This pose already exists.");
    } finally {
        SQLWarning w;
        try {
            for (w = connection.getWarnings(); w != null; w = w.getNextWarning())
                    System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "An unknown error in the yoga design program has occurred.");
        }
    }
}

// Insert statement that inserts a new section into warmup, work or restore sections 
public void insertNewSection(String sectionType, String sectionName, ArrayList<String> poses) {
    System.out.println("insertNewSection method was called");
    int maxColumns = countColumnsInTable(sectionType);
    poseArray = new String[poses.size()];
    poseArray = poses.toArray(poseArray);
    if (poseArray.length == 0)
        JOptionPane.showMessageDialog(null, "There are no poses in this section. Please add poses.");

    // Create a list of columns of the table for the INSERT statement
    StringBuilder columns = new StringBuilder(sectionType + "_name");
    for (int c = 1; c < maxColumns; c++) 
        columns.append(", pose_" + c);

    // Create a string list of poses, separated by commas, from the array
    StringBuilder values = new StringBuilder();
    values.append("'" + poseArray[0] + "'");
    for (int v = 1; v < poseArray.length - 1; v++)
        values.append(", '" + poseArray[v] + "'");
    // make sure query uses correct number of columns by padding the query with NULL
    for (int i = poseArray.length; i < maxColumns; i++) 
        values.append(", NULL");
    String posesToAddToSection = values.toString();

    // The string containing the entire insert statement
    String insert = "INSERT INTO " + sectionType + " (" + columns + ") VALUES ('" + sectionName + "', " + posesToAddToSection + ")";

    // Run the insert
    try {
        statement = connection.createStatement();
        statement.executeUpdate(insert);
    } catch (SQLException e) {
        System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
        JOptionPane.showMessageDialog(null, "An error in the yoga design program has occurred. SQLException: " + 
                e.getMessage() + ":" + e.getSQLState());
    } finally {
        SQLWarning w;
        try {
            for (w = connection.getWarnings(); w != null; w = w.getNextWarning())
                    System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "An unknown error in the yoga design program has occurred.");
        }
    }
}

    // Statement that deletes rows from tables
public void deleteRow(String tableName, String columnName, String rowName) {

    String delete = "DELETE FROM " + tableName + " WHERE " + columnName + " = '" + rowName + "'";
    // Run the insert
    try {
        statement = connection.createStatement();
        statement.executeUpdate(delete);
        System.out.println("Delete statement was run on Java's end.");
    } catch (SQLException e) {
        System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
        JOptionPane.showMessageDialog(null, "Sorry, something went wrong: SQLException: " + 
        e.getMessage() + ":" + e.getSQLState());
    } finally {
        SQLWarning w;
        try {
            for (w = connection.getWarnings(); w != null; w = w.getNextWarning())
                    System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

// Method for getting the number of columns in a table using metadata
public int countColumnsInTable(String sectionType) {
    int count = 16;
    try {
        // System.out.println(sectionType);
        statement = connection.createStatement();
        rset = statement.executeQuery("SELECT * FROM " + sectionType);
        rsMetaData = rset.getMetaData();
        count = rsMetaData.getColumnCount();
        // System.out.println("Column count is " + count);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return count;
}

// Close the database and release resources
public void closeDatabase() {
    try {
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

这是错误列表的开头:

java.sql.SQLException: Before start of result set
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:855)
at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5773)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5693)
at YogaDatabaseAccess.listPosesInSection(YogaDatabaseAccess.java:125)
at YogaSectionDesigner$5.actionPerformed(YogaSectionDesigner.java:229)

最佳答案

也许你可以检查一下:

ResultSet exception - before start of result set

遇到了同样的问题。就这样解决了。

关于java - 在 Java 程序中开始结果集之前获取 SQL 错误 1078,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16461635/

相关文章:

java - 如何传入一个类来创建一个类数组?

mysql - MySQL Workbench 中的正向工程 EER 图

java - 处理大数据对象,应该释放Clob吗?

java - MyBatis。选择错误

java - 错误 4956 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-00923: FROM keyword not found where expected

java - boolean 值不起作用,需要修复吗?

java - SpringMVC : ExceptionHandler fails to catch my custom exception

mysql - 属性神秘地设置为 1 的 id

php - mysql 或 sqlite 以及设计选择的安全性

java结果集覆盖