java - MySQL 表中的 ArrayIndexOutOfBoundsException

标签 java indexoutofboundsexception

我在 MySQL 中创建了一个包含一张表的数据库:

CREATE DATABASE iac_enrollment_system;

USE iac_enrollment_system;

CREATE TABLE course(
    course_code CHAR(7),
    course_desc VARCHAR(255) NOT NULL,
    course_chair VARCHAR(255),
    PRIMARY KEY(course_code)
);

我使用以下 Java 代码将记录插入表中:

// Insert multiple records with user input into a table
// With separate methods

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

class InsertSQL3 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/iac_enrollment_system";
static final String USER = "root";
static final String PASS = "1234";

static int no_of_records;
static String[] saCourseCode = new String[no_of_records];
static String[] saCourseDesc = new String[no_of_records];
static String[] saCourseChair = new String[no_of_records];

static Connection conn = null;
static Statement stmt = null;

static void getInput() {
    Scanner scn = new Scanner(System.in);
    
    // Get number of records
    System.out.print("How many records do you want to insert? ");
    no_of_records = scn.nextInt();
    scn.nextLine();
    
    // Get values
    for(int i = 0; i < no_of_records; i++) {
        System.out.print("\nEnter course code: ");
        saCourseCode[i] = scn.nextLine();

        System.out.print("Enter course description: ");
        saCourseDesc[i] = scn.nextLine();

        System.out.print("Enter course chair: ");
        saCourseChair[i] = scn.nextLine();
    }
}

static void executeQuery() {
    System.out.print("\nInserting records into table...");
    
    try {
        stmt = conn.createStatement();

        for(int i = 0; i < no_of_records; i++) {
            String sql = "INSERT INTO course(course_code, course_desc, course_chair)" +
                "VALUES(?, ?, ?)";

            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, saCourseCode[i]);
            ps.setString(2, saCourseDesc[i]);
            ps.setString(3, saCourseChair[i]);
            ps.executeUpdate();
        }

    } catch(SQLException se) {
        se.printStackTrace();
    }
        
    System.out.println(" SUCCESS!\n");
}

public static void main(String[] args) {
    try {
        Class.forName("com.mysql.jdbc.Driver");

        System.out.print("\nConnecting to database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        System.out.println(" SUCCESS!\n");
        
        getInput();
        executeQuery();

    } catch(SQLException se) {
        se.printStackTrace();
    } catch(Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if(stmt != null)
                conn.close();
        } catch(SQLException se) {
        }
        try {
            if(conn != null)
                conn.close();
        } catch(SQLException se) {
            se.printStackTrace();
        }
    }
    System.out.println("Thank you for your patronage!");
  }
}

在我输入类(class)代码(例如 BSCS-SE)后,它返回以下错误: out_of_bounds

为什么越界了?非常感谢您的帮助。谢谢。

最佳答案

Java 中数字基元的默认值为 0,因此数组 saCourseCode 是一个大小为零的数组,无法为其分配任何值。接受 no_of_records

后初始化数组
no_of_records = scn.nextInt();
saCourseCode = new String[no_of_records];

这也适用于数组 saCourseDescsaCourseChair

编辑:

这是一个用于初始化数组的模板。省略了一些代码,但您应该能够弄清楚其余的内容:

class InsertSQL3 {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/iac_enrollment_system";
    static final String USER = "root";
    static final String PASS = "***";

    private int noOfRecords;
    private String[] saCourseCode;
    private String[] saCourseDesc;
    private String[] saCourseChair;

    private Connection conn = null;
    private Statement stmt = null;

    private Scanner scn;

    public InsertSQL3() {
        scn = new Scanner(System.in);
    }

    private void initConnection() {
       ...
    }

    private void getInput() {

        // Get number of records
        System.out.print("How many records do you want to insert? ");
        noOfRecords = Integer.parseInt(scn.nextLine());

        saCourseCode = new String[noOfRecords];
        saCourseDesc = new String[noOfRecords];
        saCourseChair = new String[noOfRecords];

        ...
    }

    private void executeQuery() {
         ...
    }



    public static void main(String[] args) {
        InsertSQL3 insertApp = new InsertSQL3();
        insertApp.initConnection();
        insertApp.getInput();
        insertApp.executeQuery();

        System.out.println("Thank you for your patronage!");
    }
}

关于java - MySQL 表中的 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18297533/

相关文章:

java - 如何在不检查大小或超出范围的情况下获取字符串的前 n 个字符?

java - JVM 错误?缓存对象字段值导致 ArrayIndexOutOfBoundsException

java - IndexOutOfBoundsException 故障排除提示

android - android galaxy的真实设备数据库文件为空点异常

java - mvn混淆器: Is there possible obfuscate dependency before copying

java - 在java中编写这种for循环的优雅方式

java - 如何缓存 Json 数据以供离线使用?

java - 意外的 IndexOutOfBoundsException

java - 如何从 JTable 获取值并添加到数据库。 Jtable 和 db 列不同

java - 为什么这个开关 block 不起作用?