List iterator returning zero - java

i am trying to iterate records from a table using the list iterator but it is returning zero records . i have used a setter getter class and trying to fetch records into a jsp page
code is as follows :
java function :
public List<product> getProducts()
{
List<product> prod=new ArrayList<product>();
try
{
conn = obj.connect();
String sql="select product.product_name , product.price , product.image_url "
+ "from category , product "
+ "where product.category_id=category.category_id and product.product_brand like 'LG%'";
rs=cs.executeQuery(sql);
while(rs.next())
{
p.setPname(rs.getString(1));
p.setPrice(rs.getString(2));
p.setImg(rs.getString(3));
}
prod.add(p);
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(Exception k)
{
k.printStackTrace();
}
return prod;
}
jsp code :
operations op=new operations();
product p=new product();
List<product> list=op.getProducts();
%>
<title>LG Mobiles</title>
</head>
<body>
<b><font color="blue">Total Records Fetched : <strong><%=list.size()%></strong></font></b>
QUERY is running fine in sql , i checked and confirmed
below is the small segment from setter getter class product.java
public void setPname(String pname)
{
this.pname=pname;
}
public String getPname()
{
return pname;
}
public void setPrice(String price)
{
this.price=price;
}
public String getPrice()
{
return price;
}

Move prod.add(p); inside the while loop. As you are not adding object everytime. Also you need to create new object of p in loop everytime.
while(rs.next())
{
product p = new product();
p.setPname(rs.getString(1));
p.setPrice(rs.getString(2));
p.setImg(rs.getString(3));
prod.add(p);
}

you have to remove , from category and product using as
String sql="select product.product_name , product.price , product.image_url "
+ "from category as product "
+ "where product.category_id=category.category_id and product.product_brand like 'LG%'"
or
you also try this one
prod=cs.executeQuery(sql);
Iterator it=prod.iterator;
while(it.next())
{
---------------
}

Related

How do i access and print out data with sql2o

So i have code block similar to this:
public class Task {
private Long id;
private String description;
private Date dueDate;
// getters and setters here
public List<Task> getAllTasks(){
String sql =
"SELECT id, description, duedate " +
"FROM tasks";
try(Connection con = sql2o.open()) {
return con.createQuery(sql).executeAndFetch(Task.class);
}
}
}
(There is also a getID method and getDesc method left out)
I am able to run something like this to get the objects in the list it returns:
Task myTask1 = Task.getAllTasks().get(0);
If i try and print the id or desc from it like so
System.out.println(myTask1.getID());
System.out.println(myTask1.getDesc());
I always get 0 and null, which is not the correct values. What do i need to do to get this to work?
If you just want to print SQL result, it is possible by invoking executeAndFetchTable() and iterate the returning org.sql2o.data.Table object. Here is the sample code:
import org.junit.Test;
import org.sql2o.Connection;
import org.sql2o.Sql2o;
public class Sql2oTest {
#Test
public void testSql2oTable() {
Sql2o sql2o = new Sql2o("jdbc:postgresql://10.9.8.7:5432/testdb", "utest", "password");
try (Connection con = sql2o.open()) {
con.createQuery("SELECT * FROM pg_catalog.pg_tables")
.executeAndFetchTable() // No entity class needed
.rows() // List<org.sql2o.data.Row>
.stream() // Java 8 stream
.forEach(row -> // print what you want
System.out.println(row.getString(1) +
", " + row.getObject(2) +
", " + row.getObject("hasindexes")));
}
}
}

How do i create hibernate mappings for this situation?

I have the following SQL query:
SELECT CONNECTIONDATE AS UNLOAD,
SUBSTR(ROUTECODE,1,(LENGTH(ROUTECODE)-2)) AS ROUTE,
COUNT(SUBSTR(ROUTECODE,1,(LENGTH(ROUTECODE)-2))) AS FREQUENCY
FROM RouteTableSynonym RC1
WHERE RC1.ROUTECONNECTIONTYPE = 'INBOUND'
and RC1.CONNECTIONTIME >= TO_TIMESTAMP('<sdate>', 'DD-MM-YYYY HH24:MI:SS')
and RC1.CONNECTIONTIME <= TO_TIMESTAMP('<edate>', 'DD-MM-YYYY HH24:MI:SS')
and RC1.LOGISTICSPOINTID in (SELECT DISTINCT RCO1.LOGISTICSPOINTID
FROM RouteOrderTableSynonym RCO1
WHERE RCO1.NAMC = '<namc>')
GROUP BY CONNECTIONDATE, SUBSTR(ROUTECODE,1,(LENGTH(ROUTECODE)-2))
ORDER BY CONNECTIONDATE, ROUTE;
All values designated by '<var_name>' are replace with the values that being queried. I also have this entity class that will store the result of this query:
import java.util.Date;
public class DD_BlackoutRouteFrequencies {
private Date rte_day;
private String route;
private int freq;
private int delayedFreq;
public Date getRte_day() {
return rte_day;
}
public void setRte_day(Date rte_day) {
this.rte_day = rte_day;
}
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
public int getFreq() {
return freq;
}
public void setFreq(int freq) {
this.freq = freq;
}
public int getDelayedFreq() {
return delayedFreq;
}
public void setDelayedFreq(int delayedFreq) {
this.delayedFreq = delayedFreq;
}
}
I execute the query like this :
try{
SQLQuery sqlquery = session.createSQLQuery(query);
sqlquery.addEntity(DD_BlackoutRouteFrequencies.class);
results = sqlquery.list();
logger.debug(results.size());
System.out.println("Frequnecy Results size: "+results.size());
}catch(Exception e){
logger.error("Exception ", e);
throw new RuntimeException("SQL Exception getting Blackout Route Frequencies: "+ e.getMessage());
}
The problem I am having is that I cannot figure out how to do the hibernate mapping for this entity to receive the results of this query which draws its results from two different tables.
Do I have to do the hibernate mapping for both table used in the query and then map the entity?
You can also get an instance of a map. e.g.:
SQLQuery sqlQuery = session.createSQLQuery(sql);
// positional parameters (using ?)
sqlQuery.setString(0, sdate);
sqlQuery.setString(1, edate);
sqlQuery.setString(2, namc);
// scalar values for each column
sqlQuery.addScalar("UNLOAD", Hibernate.STRING);
sqlQuery.addScalar("ROUTE", Hibernate.STRING);
sqlQuery.addScalar("FREQUENCY ", Hibernate.INTEGER);
sqlQuery.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
List<Map<String, Object>> list = sqlQuery.list();
for (Map<String, Object> map : list) {
System.out.println(map.get("UNLOAD"));
System.out.println(map.get("ROUTE"));
System.out.println(map.get("FREQUENCY"));
}

Incrementing values in jdbc

I have a class called DatabaseInterface where I have my tables created over there with get Customer as a method which is as follows:
public static Customer getCustomer(long id) {
System.out.println("Get customer " + id);
Customer customer = new Customer();
try {
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM customer where id = " + id);
if (resultSet.next())
{
long cId = resultSet.getLong("id");
String name = resultSet.getString("name");
long tagNo = resultSet.getLong("tagNo");
String email = resultSet.getString("EMAIL");
String telephoneNo = resultSet.getString("telephoneNo");
int noOfTimesRecycled = resultSet.getInt("No of Times Recycled");
customer = buildCustomer(cId, name, tagNo, telephoneNo, email, noOfTimesRecycled);
System.out.println(customer);
}
} catch (SQLException ex) {
System.out.println("Error in getting customer");
ex.printStackTrace();
}
return customer;
}
I have a text file that reads value of the tagNo and each time there's a new entry for a tag it increments the value of noOfTimesRecycled.
Am doing that in a new class called UpdateTag. So I called the method getCustomer from DatabaseInterface class first and then will move on with the updates but getting error.
package com.qmul.rfid.service;
import java.util.List;
import com.qmul.rfid.dataaccess.DatabaseInterface;
//import com.qmul.rfid.dom.Customer;
import com.qmul.rfid.reader.ImportTagJob;
public class UpdateTag {
List<String> fileList = ImportTagJob.fetchData();
{
try{
for (String tag : fileList)
{
DatabaseInterface.getCustomer(long id); //Getting error on long id -Syntax error on token "long", delete this token
System.out.println(tag);
}
}
catch (IllegalArgumentException ex)
{
ex.printStackTrace();
}
}
}
Any idea why?

Spring mvc category tree

I have category tree.My category has n number subcategories.How do list recursion category on jsp?
List<Category> categories = categoryService.findAll();
modelMap.put("categories",categories)
Using JSTL, try something like this:
Simple List of Items
<c:forEach var="category" items="${categories}">
${category.id} -> ${category.name}
</c:forEach>
Nested List of Items
If you have nested categories, try something like the following custom tag.
public class CategoryDisplayTag extends TagSupport
{
public int doStartTag() throws JspException
{
Category rootCategory = new Category();
printEachCategory(rootCategory);
return SKIP_BODY;
}
private void printEachCategory(Category category)
{
JspWriter out = pageContext.getOut();
try
{
out.write("Category: " + category.getName());
for (Category c : category.getCategories())
{
out.write("Sub-category: " + c.getName());
printEachCategory(c);
}
}
catch (IOException e1)
{
throw new RuntimeException(e1);
}
}
}

League Table - SQL Query/JDBC Issue

I currently have a very basic app that interacts with a database (Using netbeans and the jdbc) so that you can add teams, players and scores. I now need to be able to display items from each table together in a League Table/Team (With players) Table etc etc.
My question is how do I go about retrieving the information from the tables and how do I display it, I am literally clueless as to how I should go about it. I'm assuming I need to do a Join or Select statement (I'm a complete SQL novice) and then use a loop to select each table entry and display it in a table somehow?
The only current working features I have are adding to the database, IE add a new team add a new player etc, displaying what is in the tables on the form is where I am stumped.
Any tips or help is much appreciated.
The code I am currently using is this; (I still need to implement a score table and adding records to that, I also created the datbase using the GUI and so have no foreign keys set, is there a way to do this WITHIN netbeans as I have no "Create Table" code anywhere.
package football.game;
/*import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;*/
import football.game.DBconnection;
import java.sql.*;
/**
*
* #author Steffan Caine
*/
public class SportsConnection extends DBconnection {
public SportsConnection(final String dbName)
{
this.connectDatabase(dbName);
}
public void insertPlayer(final Integer PLAYERNUM,
final String PLAYERNAME, final String PLAYERPOS, final Integer TEAMNUM)
{
final String insertStmt = "INSERT INTO APP.PLAYERS (PLAYERNUM, PLAYERNAME, PLAYER_POS, TEAM_ID) VALUES (?,?, ?, ?)";
try
{
PreparedStatement pstmt = getConnection().prepareStatement(insertStmt);
pstmt.setInt(1, PLAYERNUM);
pstmt.setString(2, PLAYERNAME);
pstmt.setString(3, PLAYERPOS);
pstmt.setInt(4, TEAMNUM);
pstmt.executeUpdate();
}
catch (SQLException sqle)
{
System.out.println("Exception when inserting player record: " + sqle.toString());
}
}
public void insertTeam(final String NAME, final String MANAGER, final int ID)
{
final String insertStmt = "INSERT INTO APP.TEAMS (TEAMNAME, MANAGER, TEAM_ID) VALUES (?,?, ?)";
try
{
PreparedStatement pstmt = getConnection().prepareStatement(insertStmt);
pstmt.setString(1, NAME);
pstmt.setString(2, MANAGER);
pstmt.setInt(3, ID);
pstmt.executeUpdate();
}
catch (SQLException sqle)
{
System.out.println("Exception when inserting team record: " + sqle.toString());
}
}
public void printAllRecords()
{
this.setQuery(retrieveQuery);
this.runQuery();
ResultSet output = this.getResultSet();
try
{
if (null != output)
{
while(output.next())
{
String PLAYERNUM = output.getString(1);
String PLAYERNAME = output.getString(2);
System.out.println (PLAYERNUM + "\n" + PLAYERNAME + "\n");
}
}
}
catch (SQLException sqle)
{
System.out.println("Exception when printing all students: " + sqle.toString());
}
}
}
The "retrieveQuery" currently returns an error message, any help getting that part to work would be great as printing the records out in a console would add some much needed (If basic) functionality.
I also have classes for each form (AddPlayer/AddTeam/Navigation) but I am not using constructors to populate the database I am instead using Methods located in a Main class, is this a bad way to go about things as I am not using "Objects" as such?
Thanks.
I see three tables: PLAYER, TEAM, and LEAGUE.
A TEAM has many PLAYERs; a LEAGUE has many TEAMs. These should be one-to-many relationships, so you'll have foreign keys. Here's an example:
CREATE TABLE PLAYER (
int id not null auto increment,
first_name varchar(80),
last_name varchar(80),
int team_id,
primary key(id),
foreign key(team_id) references TEAM(id)
);
CREATE TABLE TEAM (
int id not null auto increment,
name varchar(80),
primary key(id)
);
So you might have Java classes like this:
package model;
public class Player {
private Integer id,
private String name;
// ctors, getters, etc.
}
public class Team {
private Integer id,
private String name,
List<Player> players;
// ctors, getters, etc.
}
You'll have a persistence layer that will have all your SQL in it:
package persistence;
public interface PlayerDao {
Player find(Integer id);
List<Player> find();
Integer save(Player p);
void update(Player p);
void delete(Player p);
}
Here's a sample implementation for PlayerDao:
package persistence;
public class PlayerDaoImpl implements PlayerDao {
private static final String SELECT_ALL = "SELECT id, name FROM PLAYER ";
private static final String SELECT_BY_ID = SELECT_ALL + "WHERE id = ?";
private Connection connection;
public PlayerDaoImpl(Connection connection) {
this.connection = connection;
}
public Player find(Integer id) {
Player p = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = this.connection.prepareStatement(SELECT_BY_ID);
ps.setInteger(1, id);
rs = ps.executeQuery();
while (rs.next()) {
Integer pid = rs.getInteger("id");
String name = rs.getString("name");
p = new Player(id, name);
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
DatabaseUtils.close(rs);
DatabaseUtils.close(ps);
}
return p;
}
}
Printing records in consoles or user interfaces would indeed be useful, but that should be done by different classes in different packages. Have a view tier that handles that stuff. Classes should do one thing well. You should think about layering your applications appropriately.

Categories