Hi I am trying to create a program that collects tasks from a database and displays them for editing. There is an issue that I am not sure how to resolve.
I want to load the several task objects with info from the database. The error only shows up when the program is actually ran.
This is the error:
Please enter a corresponding number: 2
This works? 1
5.6.25-log
This works? 2
This works? 3
This works? 4
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at mytaskapp.DatabaseConnectTaskSelect.Connect(DatabaseConnectTaskSelect.java:65)
at mytaskapp.Display.TaskOutput(Display.java:175)
at mytaskapp.Display.StartScreen(Display.java:51)
at mytaskapp.MyTaskApp.main(MyTaskApp.java:16)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)
My code is
public static void Connect()
{
Connection con = null;
Statement st = null;
ResultSet rs = null;
Statement stu = null;
ResultSet rsu = null;
PreparedStatement pst = null;
String url = "jdbc:mysql://localhost:3306/tasks";
String user = "root";
String password = "cinder";
try {
int index = 1;
TaskObject[] task = new TaskObject[index];
System.out.println("This works? 1");
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
if (rs.next()) {
System.out.println(rs.getString(1));
}
System.out.println("This works? 2");
pst = con.prepareStatement("SELECT mainTaskString, timeCreated, dateCreated, timeDue, dateDue, "
+ "notes, project, catagory, taskLength, priority, remind1TimeDue, remind1DateDue, "
+ "remind2TimeDue, remind2DateDue FROM usertasks");
rsu = pst.executeQuery();
System.out.println("This works? 3");
while (rsu.next()) {
index = 1;
//task[index] = new TaskObject(index);
System.out.println("This works? 4");
task[index].setTask(rsu.getString("mainTaskString"));
System.out.println("This works? 4.1");
task[index].setDateCreated(rsu.getString("timeCreated") + " " + rsu.getString("dateCreated"));
System.out.println("This works? 4.2");
task[index].setDateDue(rsu.getString("timeDue") + " " + rsu.getString("dateDue"));
System.out.println("This works? 4.3");
task[index].setNotes(rsu.getString("notes"));
task[index].setProject(rsu.getString("project"));
task[index].setCatagory(rsu.getString("catagory"));
task[index].setTaskLength(rsu.getInt("taskLength"));
task[index].setPriority(rsu.getInt("priority"));
task[index].setRemind1DateDue(rsu.getString("remind1TimeDue") + " " + rsu.getString("remind1DateDue"));
task[index].setRemind2DateDue(rsu.getString("remind2TimeDue") + " " + rsu.getString("remind2DateDue"));
System.out.println("This works? 5");
System.out.println("Your Task: " + task[index].getTask() + "\n" + " Date Created: " + task[index].getDateCreated() + " Date Due: " + task[index].getDateDue() +
" Your Notes: " + task[index].getNotes() + "\n" + " Project: " + task[index].getProject() + " Catagory: " + task[index].getCatagory() + " The minutes needed to complete: " + task[index].getTaskLength() +
" Priority: " + task[index].getPriority() + " Reminder 1: " +
task[index].getRemind1DateDue() + " Reminder 2: " + task[index].getRemind2DateDue() + "\n");
System.out.println("This works? 6");
//index++;
}
You can define size of Array only once. So make sure you define it proper otherwise it will throw ArrayIndexOutOfBoundsException when you try to put values more then specified in the size.
In your code you have specified size as 1. So when you try to put more then 1 value in your task array, you will get this exception.
So make sure you specify enough size say 50.
But I would recommend to use List instead of Array, as it gives flexibility automatically increase size without specifying size. You can refer Array or List in Java.
You can make following changes in your code
Declare taskList instead of task array.
List<TaskObject> taskList = new ArrayList<TaskObject>();
In while loop create object of TaskObject, set values into it and then add it to taskList.
TaskObject taskObject = null;
while (rsu.next()) {
taskObject = new TaskObject();
taskObject.setTask(rsu.getString("mainTaskString"));
//set remaining value
//Add taskObject in List
taskList.add(taskObject);
}
int index = 1;
TaskObject[] task = new TaskObject[index];
This will create the array of the object of type TaskObject with the size 1. That means it can have only task[0]. If you give task[1] it is array out of bound.
So in the while loop it should be (according to your exp)
index = 0;
System.out.println("This works? 4");
task[index].setTask(rsu.getString("mainTaskString"));
If your query is returning fixed number of rows then it is advisable to use array else use arraylist.
Related
Here, resultSet.getInt() doesn't work, but I do not know what is wrong with my code.
I want to increment the value of the column (with the name as the variable 'attendance'). Using the SELECT statement I want to read the current value and by using UPDATE I want to increment the corresponding value by 1. But the problem is that int a = r.getInt("'" + attendance + "'"); doesn't work. It always returns the value 0 although the current value isn't 0 (e.g. 1). What is wrong with my code?
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:"+ x +".db");
s = c.createStatement();
r = s.executeQuery("SELECT '" + attendance + "' FROM viewer WHERE name = '" + name + "' AND year = '" + year + "'");
while (r.next()){
int a = r.getInt("'" + attendance + "'");
int b = 1 + a;
String sql = "UPDATE viewer SET '" + attendance + "' = ? WHERE name = ? AND year = ? ";
p = c.prepareStatement(sql);
p.setInt (1,b);
p.setString (2,name);
p.setInt (3,year);
p.executeUpdate();
}
p.close();
c.close();
// r.getInt() value always 0
}
catch (ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
Since you wrap the name of the column in single quotes, it is considered as the string literal 'attendance' and not the name of the column which is the value of the variable attendance.
Change to:
"SELECT " + attendance + " FROM viewer WHERE name = '" + name + "' AND year = '" + year + "'"
(why do you concatenate the arguments name and year? Use placeholders ? just like the UPDATE statement)
and
"UPDATE viewer SET " + attendance + " = ? WHERE name = ? AND year = ? "
and
int a = r.getInt(attendance);
since you only have 1 column, you can use column index, instead of column names
int a = r.getInt(0);
So, I have something like this:
System.out.println("Enter owner's IC no. or plate no. : ");
String update = in.nextLine();
String sql = String.format("SELECT * FROM `vehicle` WHERE ic='%s' OR plate ='%s'",update,update);
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()) {
System.out.println("RegNo." +"\t\t"+ "Name" + "\t\t" + "IC" +"\t\t" + "Plate No." + "\t" + "Color" + "\t\t" + "Year" + "\t\t" + "Make" + "\t\t" + "Model" +"\t\t"+ "Capacity" + "\t" + "Type" +"\t\t" + "Max Load");
}
else {
System.out.println("IC and PLate No. not found....");}
while (rs.next()) {
regno = rs.getInt("regno");
name = rs.getString("name");
ic = rs.getString("ic");
plate = rs.getString("plate");
color = rs.getString("color");
year = rs.getInt("year");
make = rs.getString("make");
model = rs.getString("model");
capacity = rs.getDouble("capacity");
type = rs.getString("type");
maxload = rs.getDouble("maxload");
System.out.println(toString());
}
What I'm trying to do is, if data is found in the database, it will then print the following table for outputs that match.
Now, It is supposed to print out every output. But, it only prints out the first one.
I believe that the following code is the cause:
if(rs.next()) {
System.out.println("RegNo." +"\t\t"+ "Name" + "\t\t" + "IC" +"\t\t" + "Plate No." + "\t" + "Color" + "\t\t" + "Year" + "\t\t" + "Make" + "\t\t" + "Model" +"\t\t"+ "Capacity" + "\t" + "Type" +"\t\t" + "Max Load");
}
else {
System.out.println("IC and PLate No. not found....");}
I also faced the same problem, when used select query with Prepared statement.
For example-
String sqlquerySELECTAgentsWithParam = " select * from AGENTS WHERE AGENT_CODE = ( ? ) ";
it returned a single row, since I've used IF condition and then while(rs.next())
I couldn't print the single row, Hence, I've used do-while loop like below in order to print the first-row result. code snippet below- hope it will help !!
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(oracelDBUrl, oracleDBUser,oracleDBPwd );
if (conn != null) { System.out.println("Connected to the Oracle DB "); }
else { System.out.println("Failed to Connect to Oracle DB "); }
PreparedStatement pstmt = conn.prepareStatement(sqlquerySELECTAgentsWithParam);
pstmt.setString(1,"<agent_id>");
ResultSet rs = pstmt.executeQuery();
boolean returnResultrs = rs.next();
System.out.println("Fetched Result is = " +returnResultrs);
if(returnResultrs)
{
do {
System.out.println("Inside Do - While Loop");
System.out.println("AGENT_CODE = " + rs.getString(1)+ "has AGENT_NAME = " +rs.getString(2));
}
while(rs.next());
}
Use MessageFormat to format the output, and the counter to determine if empty result set, like so:
String strFormat = "RegNo. {0}\tName {1}\tIC {2}\tPlate No. {3}\tColor {4}\tYear {5}\tMake {6}\tModel {7}\tCapacity {8}\tType {9}\tMax Load {10}");
int counter = 0;
while (rs.next()) {
counter++;
regno = rs.getInt("regno");
name = rs.getString("name");
ic = rs.getString("ic");
plate = rs.getString("plate");
color = rs.getString("color");
year = rs.getInt("year");
make = rs.getString("make");
model = rs.getString("model");
capacity = rs.getDouble("capacity");
type = rs.getString("type");
maxload = rs.getDouble("maxload");
System.out.println(MessageFormat.format(strFormat, regno, name, ic, plate, color, year, make, model, capacity, type, maxload));
}
if (counter == 0) {
System.out.println("IC and PLate No. not found....");
}
So I see two issues here. The biggest one is this:
System.out.println(toString());
That calls the .toString() method on the current class, which will not output any of the data from your ResultSet. At least, not based on any of the code you've shown. You're storing all of the values coming back from the ResultSet in variables, but those variables don't appear to be getting used anywhere. You need to get those variables to your .println() somehow.
The second issue is that rs.next() moves the cursor forward one row. So when you do this:
if(rs.next()) {
That causes you to skip the first row. This is actually kind of tricky to fix, because there's no good way to tell whether or not a ResultSet is empty without calling .next(). The way I'd probably handle this is to pull all of the results into objects in a list, and then do all the printing based on the list, and not on the ResultSet itself.
This is of course parts of a larger code. It will compile with no problem, but when I call this method I get the error
"syntax error near or at "."" at the position of stmt.executeQuery(SQL).
I would really appreciate the help!
private void Component() {
try {
Statement stmt = con.createStatement();
String SQL = "SELECT component.*, stock.amount_of_component, component.price component.component_type "
+ "FROM component JOIN stock "
+ "ON component.id = stock.component_id "
+ "ORDER BY component.component_type";
ResultSet rs = stmt.executeQuery(SQL);
rs.next();
int id = rs.getInt("ID");
int amount_of_component = rs.getInt("Amount");
String name = rs.getString("Name");
double price = rs.getDouble("Price");
String component_type = rs.getString("Type");
System.out.println(" " + id + amount_of_component + " " + name + " " + price + " " + component_type);
} catch (SQLException err)
{
System.out.println(err.getMessage());
}
}
Typo, missing a comma in the query between component.price and component.component_type :
SELECT component.*, stock.amount_of_component, component.price, component.component_type
FROM component JOIN stock
ON component.id = stock.component_id
ORDER BY component.component_type
Edit: To read the whole result set, put this cycle instead of rs.next()
while(result.next()) {
int id = rs.getInt("ID");
int amount_of_component = rs.getInt("Amount");
String name = rs.getString("Name");
double price = rs.getDouble("Price");
String component_type = rs.getString("Type");
System.out.println(" " + id + amount_of_component + " " + name + " " + price + " " + component_type);
}
Edit2: To print the header, you have to do it manually by putting a System.out.println(" id amount_of_component name price component_type "); before the while.
You missed a comma between 'component.price' and 'component.component_type'
This is the code:
#Override public void update(){
Statement stmt = null;
String company = "";
try {
Connect conn = new Connect();
stmt = conn.makeStatement();
// This creates the SQL statement to update an existing student.
System.out.println("Update employee"
+ " Set employeeID = employeeID,"
+ " firstName = firstName,"
+ " lastName = lastName,"
+ " paRating = paRating,"
+ " status = status,"
+ " manager = managerr,"
+ " level = level,"
+ " company = company"
+ " WHERE employeeID = " + get EmployeeID()
+ "Limit 1");
stmt.execute("Update employee"
+ " Set employeeID = employeeID,"
+ " firstName = firstName,"
+ " lastName = lastName,"
+ " paRating = paRating,"
+ " status = status,"
+ " manager = managerr,"
+ " level = level,"
+ " company = company"
+ " WHERE employeeID = " + get EmployeeID()
+ "Limit 1");
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
System.err.println("Unable to update employee in the database.");
} finally {
}
System.out.println("Employee successfully updated to the database.");
}
I am assuming I have missed something simple & obvious that i just can't see.
This query doesn't update anything - it just sets a whole lot of columns to their existing values. If you want to update them to something else, you'd better pass those "something else" values in somehow.
Two things I note, you probably want a space between getEmployeeID() and Limit 1; Also, assuming you're not running with autoCommit enabled, you need to call Connection.commit(). Finally, you should close your connection and statement objects in the finally block.
I have the sample code.
public void UpdateTable1() {
for (int t = 0; t < 20; t++) {
if (consumer == 1 && number == 1 && provider1 == 31 && feedback == 1) {
try {
Class.forName(driverName);
con = DriverManager.getConnection(url + dbName, "root", "mysql");
try {
Statement st = con.createStatement();
int val = st.executeUpdate("INSERT Consumer1 VALUES ("
+ 31 + "," + "'Printer'" + ", " + 1 + " " + ")");
System.out.println("1 row affected");
} catch (SQLException s) {
System.out.println("SQL statement is not executed!");
}
con.close();
}
}
}
}
I want to insert the same set of values(31,printer,1) into the table consumer2,consumer3.Is it possible without using another try catch statements...Please help me.
I hope I'm not offending, but are you sure you fully understand how try-catch works?
The reason that the try catch statement is inside the for for t loop, is (likely) that someone wanted to ensure that one failure will not prevent other iterations of the loop from taking place. You could end up with corrupted data that way.
The decision you have to make is whether you want to do all three insertions under the same try-catch or not.
To easily do three insertions, do a loop on i from 1 to 3, and every time create a different statement, by adding strings, so that the first time the table is Consumer1, the second time it is Consumer2, etc. Put the whole loop inside the try catch, or put the-try-catch inside the body of the loop.
You could replace
"INSERT Consumer1 VALUES ("
with
"INSERT INTO Consumer" + (t + 1) + " VALUES ("
I'm a little unclear on this one. Is there some restriction on how many statements you can create per connection? Or will the connection close down after each update is executed?
If not, then this should work
Statement st2 = con.createStatement();
int val = st.executeUpdate("INSERT Consumer2 VALUES ("+ 31 + "," + "'Printer'" + ", " + 1 + " " + ")");
Statement st3 = con.createStatement();
int val = st.executeUpdate("INSERT Consumer3 VALUES ("+ 31 + "," + "'Printer'" + ", " + 1 + " " + ")");
if the connection closes down or you can only do one statement at a time, then I guess you could move the whole thing to a private method and then call it with different parameters, something like:
private boolean doInsert(String tableName) {
con = DriverManager.getConnection(url + dbName, "root", "mysql");
try {
Statement st = con.createStatement();
int val = st.executeUpdate("INSERT " + tableName + " VALUES ("
+ 31 + "," + "'Printer'" + ", " + 1 + " " + ")");
System.out.println("1 row affected");
return true;
} catch (SQLException s) {
System.out.println("SQL statement is not executed!");
return false;
}
}