resultSet iterating through rows within the same line - java

Ok that may not make much sense so I'll try and clarify with code, I've got a basic Result set like so: -
ResultSet results = stmt.executeQuery(constants.execQueueSQL());
I then want to iterate through this with a while loop like so: -
while (results.next()){
String val1 = results.getString("col 1");
String val2 = results.getString("col 2");
String val3 = results.getString("col 3");
}
Now, when I debug this within eclipse I can see that before executing the while line the currentRow is already showing as 1 in results, and as I step to each line within the while the currentRow count increases by 1!!
I know that I have 4 rows returned but by the time I get to retrieving col 3 I'm already out, and all subsequent values are wrong as they are being obtained from separate lines, why is this...?

Related

Problems with reading SQL row with java

I'm working on a java program with an sql database that is a pokemon. I am having problems with putting a row of the database into an array. Here's the part of my code that's causing the problem.
String query2 = "SELECT * " +
"FROM Pokedex.typea, Pokedex.Pokemon where Pokemon.ID = " + pk +
" AND type1 = type_name";
java.sql.Statement st2 = con.createStatement();
ResultSet rs2 = st2.executeQuery(query2);
int i = 2
while(rs2.next() && i<19) {
weaka[i-2] = rs2.getInt(i);
System.out.println(weaka[i-2]);
i++;
}
and here is the row that query2 returns(I tested this with mysql workbench):
Fire 1 0 0 0 1 0 1 0 0 1 -1 1 0 0 0 -1 1 -1 4 Charmander 39 52 43 60 50 65 309 Fire null Blaze null Solar Power NULL
I was hoping that this code would put the values from columns 2 through 18 into the array "weaka", but all the code does is continually do
weaka[i-2] = rs2.getInt(i);
System.out.println(weaka[i-2]);
but it never increments i, never reads the contents of any other column, and never ends. The program just print "1" a couple hundred times and then crashes. Why is the i not iterating?
Can someone help me figure out how to get my code to go down the row and read the contents of column 2 through 18 into the array? Thanks
EDIT: Thanks for both answers. They both worked to get the array reading the row, but the process still goes on longer than it should with both answers. it's like it reads the row multiple times. The code that I gave you was not in a loop, so why is it reading the row multiple times?
also Pokemon.ID is the primary key of my schema, so the query will only return one row.
The ResultSet.next() method attempts to read a row from the result set and returns true if it manages. What you're doing:
while(rs2.next() && i<19) {
weaka[i-2] = rs2.getInt(i);
System.out.println(weaka[i-2]);
i++;
}
is reading a row, putting the first value into an array, and read the next row. But there isn't a next row, so the execution stops there and then.
Instead, do this:
if (rs2.next()) {
for (int i=2; i < 19; i++){
weaka[i-2] = rs2.getInt(i);
System.out.println(weaka[i-2]);
}
}
If there is more than one row to read, you'll need to handle that, too.

Java Mysql table data output formatting

Here is my MySql table:
I want to show the output of the query in commandline as below:
I have written the code below to loop but I am getting only the first row, What i have to modify ??
ResultSet rs2 = stmt.executeQuery(table_retrive);
String[] cols = new String[itemList.size()];
int[] rec =new int[itemList.size()];
for (int i = 0; i < itemList.size(); i++) {
while (rs2.next()) {
cols[i] =(String) itemList.get(i);
rec[i] = rs2.getInt(cols[i]);
System.out.println(rec[i]+" ");
}
}
Your two loops are wrong. Start at i=0 and then iterate once over the whole ResultSet, filling yor first array position. When this is done, i is incremented and you try to iterate the ResultSet a second time but the cursor is at the end of the ResultSet, so rs2.next() returns false and the code will not be executed.
So you have two Solutions:
Handle the loops correctly. Unfortunately I do not know, what you are trying to do anyways because this is some C-like code without OOP, which doesn't show semantics and then you have this itemList which seems to hold preset values and you read out of this list, which column to take for the i-th position. This seems odd. Maybe switching the loops does the desired: Start with the while and nest the for.
Reset the cursor of the ResultSet after the while with rs2.beforeFirst(). WARNING: This could throw a SQLFeatureNotSupportedException. Not all Databases can move the cursor backwards. This is of course a very ugly solution, since you should first parse the whole row a once.
Try to use printf() Or format() method. It is same as printf method in c lang. you can pass parameters and difference. Look at link1
And link 2
Example : System.out.printf("%d%5s%10d", 5,"|",10);
output : 5 | 10
Using this the I got all the values but in one row :
while (rs2.next()) {
for (int i = 0; i < itemList.size(); i++) {
cols[i] =(String) itemList.get(i);
rec[i] = rs2.getInt(cols[i]);
System.out.print(rec[i]+" ");
}
}
But I need to divide like the rows.
Usage of the inner loop is your problem.
You can enhance your code to remove the usage of the second loop in your code, it basically does nothing. You can loop over your result set and in the same loop using the incremented variable to persist the values accordingly.
The code shown half implemented in your question, hence it will be difficult to give you exactly what need to be done. Nevertheless, here's an attempt to resolve the problem for you:
while (rs2.next()) {
System.out.println(rs2.getInt(1) + "\t |" + rs2.getString(2) + "\t |" + rs2.getString(3));
}
Based on the column names from the table in the question, assuming that column2 and column3 are String's.
You can add the necessary details to this code to complete it according to your usecase, but I've just taken the example of showing a record in one line.
EDIT:
OP has his own way of programming, but to satisfy his question in the comment - this is how you can do it.
while (rs2.next()) {
for (int i = 0; i < itemList.size(); i++)
{
cols[i] =(String) itemList.get(i);
rec[i] = rs2.getInt(cols[i]);
System.out.print(rec[i]+"\t |");
}
System.out.println();
}

How to use loop inside if statement

HasbroIssuanceDateData data1 = extractedDateData.get(c);
if (data.getOpeningBankReference().equals(data1.getOpeningBankReference())) {
data1.getOpeninbankRefernce();
data1.getPoNumber()).concat(DELIMETER));
}
I have a very simple question. I want to run a loop inside the if statement to get all rows that satisfy the if condition. Since there can be multiple rows with the same data1.getOpeningBankReference(). How would I do that?
For example in data1 there are 100 rows. I want that once it enters the if statement, it will give me all 5 rows as results (assuming there are 5 rows with the same OpeningBankRef) where data.getOpeningBankReference().equals(data1.getOpeningBankReference()) and then exit the if statement.
Maybe you need your for outside the if and another inside. So you can compare all the rows with your data.getOpeningBankReference()
for (Row row: rows) {
HasbroIssuanceDateData data1 = extractedDateData.get(row);
if (data.getOpeningBankReference().equals(data1.getOpeningBankReference())) {
for (Row anotherRow: anotherRows) {
//here you have all the rows you need.
}
}
}

How to parse a log file in Java?

I have a file that has this two rows of data.
Jan 1 22:54:17 drop %LOGSOURCE% >eth1 rule: 7; rule_uid: {C1336766-9489- 4049-9817-50584D83A245}; src: 70.77.116.190; dst: %DSTIP%; proto: tcp; product: VPN-1 & FireWall-1; service: 445; s_port: 2612;
Jan 1 23:02:56 accept %LOGSOURCE% >eth1 inzone: External; outzone: Local; rule: 3; rule_uid: {723F81EF-75C9-4CBB-8913-0EBB3686E0F7}; service_id: icmp-proto; ICMP: Echo Request; src: 24.188.22.101; dst: %DSTIP%; proto: icmp; ICMP Type: 8; ICMP Code: 0; product: VPN-1 & FireWall-1;
May I really know what's the code to parse them into different columns? One problem is
eth1 rule:7;
eth1 inzone: External; outzone: Local;
I want to let them fall under the same column. I really need some desperate help as I have no knowledge of programming and I'm tasked to do this ><
You'd probably start with Java's split function for strings:
Oracle Doc
Look at example 3
I assume you could lump your first column as everything from the start to '>' after %LOGSOURCE%. I'm also guessing there are other columns that would be lumped together and that in the end you'd only expect a certain amount of columns per row.
You could use code like this:
//a line of the log can be split on '>' and ';' for the other columns of interest
//logLine is a line off the your log, I'm assuming it's a string object
string[] splitLine = logLine.split("[>;]+");
//I'm pretending there are 7 columns, for simplicity sake I'm using an ArrayList
// of string arrays (ArraList<string[]>) that would get declared
//above all this called logList
string[] logEntry = new string[7];
//Save the time stamp of the log entry by iterating through splitLine
for(int counter1 = 0; counter1 < splitLine.length; counter1++)
{
//Timestamp column
if(counter1 == 0)
logEntry[0] = splitLine[counter1];
//First column
if(counter1 == 1)
logEntry[1] = splitLine[counter1];
//Logic to determine what needs to get appended to second column,
//could be many if statements
if(...)
logEntry[1] += splitLine[counter1];
//Logic to determine what starts third column
if(...)
logEntry[2] = splitLine[counter1];
//Logic to determine what needs to get appended to third column,
//could be many if statements
if(...)
logEntry[2] += splitLine[counter1];
//And so on... till you fill all your columns up or as much as you want
}
//Add your columned log to your list for use after you've parsed up the file
logList.add(logEntry);
You'd probably stick all this logic in a for loop that continually grabs a line off your log into the logLine string used at the top of the code sample. It's not the most efficient way, but it's pretty straightforward. Hopefully this gives you a start to approaching your problem.

Function works only with hard coded values

This is the code I am working on:
if(connection.doDatabaseRead(findSQL))
{
ResultSet retRES = connection.getResultSet();
int i = 0;
// did we find anything
while( retRES.next() )
{
//read result from query
suiteNum.add(retRES.getString(i)); // this is the problem
i++;
//let other threads breathe
Thread.yield();
}
}
suiteNum is a string vector
When I try to add the database results to the vector the code crashes with this error.
java.sql.SQLException: Column Index out of range, 0 > 1.
I have the same piece of code working elsewhere in the program but I use real numbers like 0, 1 and 2 instead of i and it works fine.
As I do not know how many results the database request will have I need it to be dynamic but it will only work hard coded.
How can I make it work with i ?
The argument to getString is the column index, not the row index as you seem to think. The function returns the value of the given column in the current row, while next advances the cursor to the next row.
You probably mean:
suiteNum.add(retRES.getString(1));
in which case you can lose i altogether.
Java ResultSet objects are 1-indexed in this regard. The first element is at 1, not 0. See the javadoc.
EDIT: That's true too, but indeed the problem is this appears to be used as a row index! it's certainly the column.
This is your problem:
i = 0;
...
retRES.getString(i);
ResultSet.getString(i) gets a String from column number i
You want something like
while(retRes.next()) {
add(retRes.getString(1);
}
column index starts from 1
As I do not know how many results the database request will have I need it to be dynamic but it will only work hard coded. How can I make it work with i
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
See Also
ResultSetMetaData
Let your i start with 1 as specified in the API docs
if(connection.doDatabaseRead(findSQL))
{
ResultSet retRES = connection.getResultSet();
int i = 1;
// did we find anything
while( retRES.next() )
{
//read result from query
suiteNum.add(retRES.getString(i)); // this is the problem
i++;
//let other threads breathe
Thread.yield();
}
}

Categories

Resources