If I try the following query in Java, Java returns without any error only the first entry of the table. But if I copy the same query to Access, Access returns all 33 entries.
Query:
SELECT Country, Sum(SumOfNumber) AS number FROM CountryList WHERE Year=2012 AND (Month=1 Or Month=2 Or Month=3) AND Entity='xxx' GROUP BY Country ORDER BY Sum(SumOfNumber) DESC
rs.last();
System.out.println(rs.getRow());
returns 1.
Any advice?
Okay guys, now I deleted therm "ORDER BY Sum(SumOfNumber) DESC" and Java returned all Countries and throwed an exception at the end "invalid cursor status"
public void doconnect(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
conn = DriverManager.getConnection(ConnectURL,user,pw);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
String query = "SELECT Country, Sum(SumOfNumbers) AS number FROM CountryList WHERE Year=2012 AND (Month=1 Or Month=2 Or Month=3) AND Entity='xxx' GROUP BY Country ORDER BY Sum(SumOfNumbers) DESC";
System.out.println(query);
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
System.out.println(rs.getString("Country"));
}
rs.close();
}
catch(Exception e){
System.err.println(e);
e.printStackTrace();
}
finally{
if(conn!=null){
try{
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
Change
rs.last();
System.out.println(rs.getRow());
to (to get all countries)
while (rs.next()) {
System.out.println(rs.getString("Country"));
}
to get results from all rows instead of just the last one.
Of course you get only one row (the last one). This is because you go directly to the last row of the ResultSet using rs.last(). Try to iterate over the ResultSet in order to get all rows returned.
To see how many rows are returned you can run query : SELECT count(*) as count FROM CountryList WHERE Year=2012 AND (Month=1 Or Month=2 Or Month=3) AND Entity='xxx' and then get the count using
while(rs.next()){
int count = rs.getInt("count");
}
rs.last() moves the cursor to the last row in the resultSet which means that after you've read the line, no more data is available, i also suggest that you use the function provided by
Keppil: while (rs.next()) {
System.out.println(rs.getRow()); }
From java API resultSet.last()
Moves the cursor to the last row in this ResultSet object.
Check it here,
remove rs.last and iterating over resultset like this
while(rs.next()) {
sysout(rs.getString("your column name"));
}
Related
i have two tables WorkSkillsPlanning(WSP) and TrainingAchieved(TA). WSP hold a list of planed training and targeted number of people to be trained e.g. ISOO:90001 10 people while TA holds the actual number of people trained as well as the actual course done. Since WSP and TA are dynamic in the sense that the data they hold is not static neither is known as training plans can change is it possible to run an intersect query on these table to find similarities i.e a course in WSP which has actually be done and recorded in TA. Store the results of the intersect query in an array e.g. MyArrayList{ISO,COMMUNICATION) these being values present in both table and use MyArrayList values to run count queries on TA to establish the number of people who would have done the course i.e ISO and COMMUNICATION and use the resultant to subtract from WSP (ISO,COMMUNICATION).
here is an example, first part
"Select QUALIFICATIONGROUP from APP.WSP intersect select COURSEBOOKED from APP.BOOKCOURSE"
which results in ISO and COMMUNICATION which i want to store in an ARRAY or variable.
second part
select count(COURSEBOOKED) from APP.BOOKCOURSE where COURSEBOOKED = Variable1
rs.getString(Count(COURSEBOOKED))
value returned == 5
re do the process again for COMMUNICATION and any other course in the array, of which after use the values returned from the count query to subtract to subtract WSP total minus TA total.
I hope this makes sense
as requested the first query is
private void updateTable(){
String sql = "Select QUALIFICATIONGROUP from APP.WSP intersect select COURSEBOOKED from APP.BOOKCOURSE";
try (Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
PreparedStatement pst = con.prepareStatement(sql);){
ResultSet rs = pst.executeQuery();
//while (rs.next()){
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
//}
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
this will give me data that is in WSP that is also present in AT and display it in a table.
the second query is now supposed to take the first value of Row one in the table and pass it to the second query as below
public void tableOne() throws Exception{
String search = "value of first row from the query ontop";
PreparedStatement pst = null;
ResultSet rs = null;
try{
Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
String sql = "SELECT COUNT(COURSEBOOKED) from APP.BOOKCOURSE where COURSE BOOKED = '"+search+"'";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
sum = rs.getString("COUNT(COURSEBOOKED)");
txtSum.setText(sum);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(this, e);
}
}
This query is supposed to run as many times as the rows produced by the first query.
this query select all the data in WSP table.
public void tableTwo() throws Exception{
String sql = "select * from APP.WSP";
try(Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
PreparedStatement pst = con.prepareStatement(sql);){
ResultSet rs = pst.executeQuery();
while(rs.next()){
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
search= rs.getString("QUALIFICATIONGROUP"); //sets the search string for tableOne();
next = rs.getInt("TOTALTRAININGPLANNED");
System.out.println(search);
System.out.println("");
System.out.println(next);
}
}
catch(SQLException e){
JOptionPane.showMessageDialog(this, e);
}
}
finally the count values from the second query are used to subtract the values
from the variable next (next= rs.getInt("TOTALTRAININGPLANNED");) generated from the last query and the finally value of next = rs.getInt("TOTALTRAININGPLANNED") - value of the second Count query are stored in an variable which will be used to reveal wether planned training and actual training are equal or different.
I hope i have clarified issues
whats wrong with my codes? I think its in the SQL but I don't know why. thank you in advance
try{
clsConnect c = new clsConnect();
Connection conn = c.makeConnection();
Statement statement = conn.createStatement();
String display = "SELECT SUM(Amountpaid) from mofficetbl";
ResultSet rs = statement.executeQuery(display);
while(rs.next()){
totalTF.setText(rs.getString("Amountpaid"));
}
}
catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
when you call this select statement; the returned column is actually called "SUM(amountpaid)" and not amountpaid so either change its alias with
"SELECT SUM(Amountpaid) as Amountpaid from mofficetbl"
You can also do:
rs.getString("Sum(Amountpaid)");
You are selecting SUM(amountpaid) and trying to access the column amountpaid, but that column doesn't actually exist in the ResultSet Try rs.getString(1) or giving the SUM a name in the select as SELECT SUM(amountpaid) as sum from msofficetbl then doing rs.getString("sum");
When I carry out the following operations:
public Product getProductById(long productId) throws DaoException {
Connection con = DBManager.connect();
PreparedStatement statement = null;
ResultSet rs = null;
try {
statement = con.prepareStatement(QUERY_PROD_BY_ID);
statement.setLong(1, productId);
rs = statement.executeQuery();
//rs.first();
Product product = new Product();
product.setProductId(rs.getLong("product_id"));
product.setProductImage(rs.getString("image"));
product.setProductBrand(rs.getString("brand"));
product.setProductModel(rs.getString("model_no"));
product.setProductPrice(rs.getFloat("price"));
product.setProductSummary(rs.getString("summary"));
product.setProductStock(rs.getInt("stock"));
product.setProductCategory(rs.getLong("category_id"));
product.setProductCreationTime(rs
.getTimestamp("product_creation_time"));
product.setProductStatus(ProductStatusState.values()[rs
.getInt("product_status")]);
product.setType(ProductType.values()[rs.getInt("type")]);
return product;
} catch (SQLException e) {
throw new DaoException(e);
} finally {
DBManager.closeAll(statement, rs);
}
}
I get an error which says
org.postgresql.util.PSQLException: ResultSet not positioned properly, perhaps you need to call next.
My ProductId is my primary key and hence only one row will be present in the ResultSet. When I set a
while(rs.next){...}
it returns me null. What should I do?
As stated in previous comments, when you execute a query that returns a result set the initial position of the cursor is before the first row of data in the result set. Calling rs.next() will move your cursor to your first row and allow you to access the data that was returned with the rs.getXXX() methods.
Can you populate more than one jTable with the same resultSet?
public void tableDisplay() {
String tableQuery = "SELECT foodQuantity,foodName FROM food ORDER BY RAND() LIMIT 3";
ResultSet rs;
PreparedStatement statement;
try {
statement = con.prepareStatement(tableQuery);
rs = statement.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
System.out.println(ex.toString());
}
}
The code compiles but the second table doesn't get any records from DB.
The point is that I need to select random items from mySql table and I want to display them in few jTables.
Without knowing too much about your code, I'd say that you need to call DbUtils.resultSetToTableModel(rs) once, and store the resulting table model in a local variable. Then, pass that local variable to the two setModel(...) methods
How I populate a JTable with resultSet
try{
playerTableModel = (DefaultTableModel)playerTable.getModel();
rs = controller.getPlayer();
while (playerTableModel.getRowCount() > 0);
int columns = playerTableModel.getColumnCount();
Object[] rows = new Object[columns];
while(rs.next()){
rows[0] = rs.getString(1);
rows[1] = rs.getString(2);
rows[2] = rs.getString(3);
rows[3] = rs.getString(4);
playerTableModel.addRow(rows);
}catch(Exception e){
e.printStackTrace();
}
Can't you just call same method for the second table too?
i have used a select command in my java program and stored its value in the result set. now while looping in the resultset i want to use a select command which will select the first 5 lines of the resultset and insert into other table. for the second time, it should select the next 5 lines and insert into the table. and for the third time, so on..
Statement s = connection.createStatement();
s.executeQuery("Select * from table1");
ResultSet res = s.getResultSet();
while(res.next()){
// here i want to select the first 5 lines of the result set and insert in the second table
}
Statement s = connection.createStatement();
s.executeQuery("Select * from table1");
ResultSet res = s.getResultSet();
while(res.next()){
// here i want to select the first 5 lines of the result set and insert in the second table
while(res.next() && (res.getRow()%5) !=0){
//select from this table
//call insert method(what selected)
}
}
I would suggest changing your query using LIMIT and using a PreparedStatement. Something like:
SELECT * FROM table1 LIMIT ?,?
This has a couple of advantages:
You are not fetching everything in one shot - can be sometimes a performance benefit if you've a lot many rows to deal with in your table
You can change pre-define the number of elements that you want to fetch in every single batch
So your code will look something like this:
PreparedStatement ps = null;
ResultSet rs = null;
final int FETCH_LIMIT = 5; //number of elements to fetch per batch
final int BATCH_LIMIT = 3; //number of batches you would want
int currentRows = 0;
try{
ps = connection.prepareStatement("SELECT * FROM table1 LIMIT ?,?");
for(int currentBatch = 0; currentBatch < BATCH_LIMIT; currentBatch++){
ps.clearParameters();
ps.setInt(1, currentRows);
ps.setInt(2, currentRows + FETCH_LIMIT);
try{
rs = ps.executeQuery();
while(rs.next()){
// do your work
}
}catch(Exception exe){
//manage exception
}finally{
//manage resultset
}
currentRows += FETCH_LIMIT;
}
}catch(Exception exe){
//Handle your exception
}
finally{
//Manage your resources
}
Please add a falg and use that is it
int i=0;
while(res.next() && i< 5){
//select from this table
//call insert method(what selected)
i++;
}
Create another insert query dynamically inside the while loop and execute it outside the while loop