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.
Related
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();
}
This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
Closed 6 years ago.
I'm getting java.sql.SQLException: Before start of result set when I try to use this code:
ResultSet user = query("SELECT `id`, `counter` FROM `accounts` WHERE `username`='test'");
int id = user.getInt("id");
int counter = user.getInt("counter");
System.out.println("Id: " + id + " | Counter: " + counter);
All I really need to do is get the values of id and counter and set it to an integer in java but I'm not sure how to do that this is the third method I've tried, is there anything else I can do to get that information? I know for a fact the problem isn't with my query method so I figured it'll be pointless to show it, this is pretty much the entire snippet. (Yes the connection is opened and closed no problem) Any help would be appreciated.
Add a call to user.next(); before trying to read the first row. You are literally before the first row. Typically, you would use a loop like
while (user.next()) {
int id = user.getInt("id");
int counter = user.getInt("counter");
System.out.println("Id: " + id + " | Counter: " + counter);
}
The ResultSet.next() Javadoc says (in part),
A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have the following peice of code:
Class.forName("oracle.jdbc.driver.Orac. leDriver");
Connectioncon=DriverManager.getCon. nection ("jdbc:oracle:thin:#localhost1521:","sys. tem","zed");
String pb=pricebox.getText();
int pbs=Integer.parseInt(pb);
final PreparedStatement ps=con.prepareStatement("selectitem code,remaining fromshoppingmallproducts wheretype='"+typebox.getSelectedIte(+. "',brand='"+brandbox.getSelectedIt. +'"');
final PreparedStatementps=con.prepareStat. ement("select itemcode,remainingfrom shoppingmallproducts where type=and brand=? and price>=?");
ps.setString(1(String)typebox.getSelect. editem();
ps.setString(2, (String)brandbox.getSelectedItem());
ps.setInt(3,pbs);
final ResultSet rs=ps.executeQuery();
rs.next();
itm=rs.getString("itemcode");
int rem=rs.getInt("remaining");
final String remm=String.valueOf(rem);
jta1.append("\n "+itm+"\n"+rem+"\n");
// jta is the name of the jtextpane used to append data
next.addActionListener(new ActionListener()
{
public void
actionPerformed(ActionEvent as)
{
try {
jta1.removeAll();
jta1.setText("");
rs.next();
String itm=rs.getString("itemcode");
int prc=rs.getInt("price");
int rem=rs.getInt("remaining");
String remm=String.valueOf(rem);
jta1.append("\n "+itm+"\n"+rem. +"\n");
drawimage(itm);
}
Now the question belongs to my next button.
As you can see, the next button will move the result set object to the next row. But I want it to perform it the other way. Now suppose, I choose Levis as brand price range 2000 and type casual shoes. Now suppose I have 3 such products. The first time when I click go button, it will show the first result. Now I want that when I click next, I want the second product with specified features, and so the third product.
Is there any way to do this? Please help me. I am really stuck with this as this is the last task in my college project.
I hope I have clearly explained every thing. Thanx
your question is not very clear. But I shall try to answer from what I understand.
first about rs.next();
This cursor is a pointer that points to one row of data in the ResultSet. Initially, the cursor is positioned before the first row. The method ResultSet.next moves the cursor to the next row. This method returns false if the cursor is positioned after the last row.
So rs.next() points to the result obtained from running your query. Let us say your table has 10 rows in total and then your query return 5 rows from that, depending on the conditions you have specified in the query(like brand,price etc ) . In such a case the rs will point to the 5 rows returned for your query. It will be pointed to before the first row of the result. when you do rs.next(); it should return the first row of the 5 rows returned as result. every rs.next() henceforth will return the next row from the 5 result rows. when rs points to 5th row and you do rs.next() then it will return false and you will know that not more rows exist to be returned.
if you are not getting value in this manner , most probable reason is your query. Try printing out all the rows returned from query using code
while (rs.next()) {
int itm = rs.getString("itemcode");
int price = rs.getString("price");
int remaining = rs.getString("remaining");
System.out.println(itm + "\t" + price +
"\t" + remaining );
}
this will print the result to the console for you to debug.
If this is printing the correct result then your query is correct. May be the problem is that rs value in jtextpane is incorrect and not pointing correctly as it should be.
PS : variable type of price should be double
Also if your question was just about order of returned result you could use ORDER BY with your query. it will allow the result to be returned according to the sorted order (ascending or descending based on a column ) of the table
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...?
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();
}
}