ArrayIndexOutOfBoundsException in MySQL Table
I created a database with one table in 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)
);
I am inserting records into the table with this Java code:
// 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!");
}
}
After I enter a course code, say, BSCS-SE, it returns this error:
Why is it out of bounds? Assistance is much appreciated. Thank you.
No comments:
Post a Comment