resultset.next() is showing output of first row only - java

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.

Related

Java resultSet getInt() returns no value

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);

Java - how to insert data into data base from txt file

I am wondering how to read in a file and insert into a table in my data base. I written this:
String customerFile = "customer.txt";
Connection myConnect = ....
Statement mySt = myConnect.createStatement();
mySt.executeUpdate(..create customer table..);
int SSN;
String CNAME;
String GENDER;
int AGE;
String PROFESSION;
String line;
String[] tokens;
FileReader file1 = new FileReader(customerFile);
BufferedReader buffer1 = new BufferedReader(file1);
//throw away first line
line = buffer1.readLine();
//continue with rest of file
while((line = buffer1.readLine()) != null)
{
tokens = line.split(",");
SSN = Integer.parseInt(tokens[0]);
CNAME = tokens[1];
GENDER = tokens[2];
AGE = Integer.parseInt(tokens[3]);
PROFESSION = tokens[4];
String insertString = "insert into customer values ( " + SSN + ", " + CNAME + "," +
GENDER + ", " + AGE + ", " + PROFESSION +")";
mySt.executeUpdate(insertString);
}
I thought this was the right way to insert into a table. However, the issue I am having with is that the variables aren't being read in the right way.
Example rows:
3648993,Emily,male,63,Consulting
5022334,Barbara,male,26,Finance
With the example above, I would want to have a table with 2 rows and 5 columns but the code I put on top gave me an error when it reaches the name. I am not sure where the issue is.
You should replace insertString with
myConnect = getConnection();
myConnect.setAutoCommit(false);
File file = new File(fileName);
fis = new FileInputStream(file);
pstmt = myConnect.prepareStatement("insert into customer( " + SSN + ", " + CNAME + "," +
GENDER + ", " + AGE + ", " + PROFESSION +") values (?,?,?,?,?)");
pstmt.setString(1, SSN);
pstmt.setString(2, AGE);
....
pstmt.executeUpdate();
myConnect.commit();
Source : Insert text file into MySQL
Make sure you put quotes around string fields, so instead of:
String insertString = "insert into customer values ( " + SSN + ", " + CNAME + "," +
GENDER + ", " + AGE + ", " + PROFESSION +")";
do:
String insertString = "insert into customer values ( " + SSN + ", '" + CNAME + "','" +
GENDER + "', " + AGE + ", '" + PROFESSION +"')";
Normally I do such things in two steps:
1) create a java class representing just one row of the textfile. This class is instantiated with a line from the txt-file and this single row is parsed and the fields are created, so I have for every single field a getter and a setter having the right fieldtype. within this class I'm able to perform tests and corrective actions if a field is wrong or even empty.
2) I create a Writer-class that reads the textfile line by line and writes every single line into the db, mostly starting with the second line, because the first line contains the header. I strictly use PreparedStatement and use batchwriting, at the end, when file looping is finished, write the batch to the DB with PreparedStatement.executeBatch() and then I close down all DB-objects.

java.lang.ArrayIndexOutOfBoundsException object array

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.

Multiplication values in JTable

I want to multiple price and quantity, so i can get the total, and put it in the table too. Can you help me? Because I already search other reference and add public Object getValueAt(int row, int column) {} but I got error so I delete it -_-
try {
String trans_id = txtNo.getText();
String menu_id = txtMID.getText();
String quantity = txtQuan.getText();
String menu_price = "";
Statement stmt;
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM menu");
stmt.executeUpdate("insert into transaction (trans_id, menu_id, menu_price, quantity)"
+ "values ('" + trans_id + "','" + menu_id + "','" + menu_price + "','" + quantity + "')");
DefaultTableModel model = (DefaultTableModel) tblMenu.getModel();
if (rs.next()) {
txtNo.setText("" + rs.getString("trans_id"));
txtMID.setText("" + rs.getString("menu_id"));
menu_price = rs.getString("menu_price");
txtQuan.setText("" + rs.getString("quantity"));
model.addRow(new Object[]{trans_id, menu_id, menu_price, quantity});
}
} catch (Exception e) {
System.out.println("Failed" + e);
}
Really need your help.
You'll have to first convert price and quantity to numerical values, multiply them, and then convert the product back to a String. You can convert the text values of price and quantity using Integer.parseInt(String s). Or Double.parseDouble if your price is not an integer...you get the idea. Do that for both price string and quantity string. Then you can get the String value by String.valueOf(whatever your price * quantity value is), assuming you want to put that value into the table as a String.

Real Time jTable column resizing

I am working on a project where I add the column names from mysql into jTable.
I want that when a name is added, the column should adjust its size according to the length of column name. I will make myself clearer, but first heres the existing code:
jTextArea1.setText(null);
tableModel.setColumnCount(0);
colwidth = 0;
try {
Class.forName("java.sql.DriverManager");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:" + GlobalParams.portvar + "/" + (String) jList1.getSelectedValue(), "" + GlobalParams.uservar, "" + GlobalParams.passvar);
Statement stmnt = (Statement) con.createStatement();
String query1 = "Use " + GlobalParams.dbvar;
stmnt.executeQuery(query1);
String query2 = "desc " + (String) jList2.getSelectedValue();
ResultSet rs = stmnt.executeQuery(query2);
while (rs.next()) {
fieldo = rs.getString("Field");
jTextArea1.append(fieldo + "\n");
}
Scanner scanner = new Scanner(jTextArea1.getText());
timeget();
jTextArea4.append(now + ": " + "/ Scanning Available feeds from table '" + (String) jList2.getSelectedValue() + "' / \n");
timeget();
jTextArea4.append(now + ": " + "/ Getting feeds from table '" + (String) jList2.getSelectedValue() + "' / \n \n");
if (scanner.hasNextLine()) {
scanner.nextLine();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
tableModel.addColumn(line);
jTable1.getColumnModel().getColumn(colwidth).setWidth(line.length());
colwidth++;
int end = jTextArea1.getLineEndOffset(0);
jTextArea1.replaceRange("", 0, end);
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
"colwidth" is a public static int and "fieldo" is a public static String.
What i want is, for ex.-> the string to be made into column is "asdadsasd123". I want that the column should adjust its width according to length of this string.
I have set the auto resize of table to off.
The table is enclosed in a scollpane. The layout of frame is Free Design.
I also did find the thread here-> Auto resizing the JTable column widths
but i cant seem to understand this code:
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component comp = table.prepareRenderer(renderer, row, column);
width = Math.max(comp.getPreferredSize().width, width);
(Yeah, I aint very experienced with java).
And I also dont want to do anything with rows for now, just resize the columns.
Here is screenshot of Default->
Here is how I want it to be->
Please help,thanks.
You can use the Table Column Adjuster.
It will adjust the column width based on the size of the header the cell data or both.

Categories