How do i access and print out data with sql2o - java

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

Related

Query isn't giving decimals on java, but it gives decimals on database

I have a query that when I execute it on database, it gives me decimals, but when I execute the same query on my app, it gives me the numbers without decimals.
I have my variables setted as "double" and they are correctly "linked" to the database, I put the code below.
Here is where I call the method:
List<DatosEstadistica> listaDatosEstadistica = facade.obtenerDatosIngresos(filtro);
The facade:
public List<DatosEstadistica> obtenerDatosIngresos(FiltroInformes filtro)
throws ServiceException {
return this.modeloService.obtenerDatosIngresos(filtro);
}
The service implement:
public List<DatosEstadistica> obtenerDatosIngresos(FiltroInformes filtro)
throws ServiceException {
try {
return this.getDao().obtenerDatosIngresos(filtro);
} catch (HibernateException he) {
throw new ServiceException(he);
}
}
And the query instructions:
public List<DatosEstadistica> obtenerDatosIngresos(FiltroInformes filtro) {
try {
StringBuffer query = new StringBuffer();
query.append("sum( decode ( a.indingdev,'R',0, "
+ "nvl(a.impingdev,0) + "
+ "nvl(a.imprecargo_ing,0) "
+ ") "
+ ") as total_recaudado, "
+ "from tableM m, table_f f, table_a a "
+ "where m.reg = f.reg");
SQLQuery querySQL = getHibernateTemplate().getSessionFactory().getCurrentSession()
.createSQLQuery(query.toString());
querySQL.setResultTransformer(Transformers.aliasToBean(DatosEstadistica.class));
return querySQL.list();
} catch (HibernateException qe) {
throw qe;
}
}
And datosEstadistica.class:
public class DatosEstadistica implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 88592689034562323954L;
private double TOTAL_RECAUDADO;
/**
* Instantiates a new datos estadistica.
*/
public DatosEstadistica() {
}
public double getTOTAL_RECAUDADO() {
return TOTAL_RECAUDADO;
}
public void setTOTAL_RECAUDADO(double tOTAL_RECAUDADO) {
TOTAL_RECAUDADO = tOTAL_RECAUDADO;
}
}
But I don't know why it doesn't give me decimals as in the same query executed on the database. Anyone can helps me, please?
EDIT:
Here is where I printed out the results, but it doesn't print the decimals, because the query List "listDatosEstadistica" return numbers without decimals:
celdaDatos.setCellValue((listaDatosEstadistica.get(i).getTOTAL_RECAUDADO()));

Getting error SQLServerException: The result set is closed

I have tried many ways but always i'm getting this error.
Actually i'm trying to access result set values from other class and for Database Query i have created a separate class.
Please do not mark this as previously asked because i got the solution only of single class.
This is my DBVerification class
public class DBVerification {
private static String DB_URL = PropertyManager.getInstance().getDB_URL();
private static String DB_USER= PropertyManager.getInstance().getDB_USER();
private static String DB_PASSWORD= PropertyManager.getInstance().getDB_PASSWORD();
private static String DBClass= PropertyManager.getInstance().getDBClass();
private static Connection connection;
public static ArrayList<ResultSet> executeStoredProcedure(String query) throws ClassNotFoundException, SQLException
{
ArrayList<ResultSet> resultset = new ArrayList<ResultSet>();
Class.forName(DBClass);
connection= DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
CallableStatement cstmt = connection.prepareCall( "{ call " + query+" }" );
//System.out.println("{ call " + query+" }");
try {
boolean results = cstmt.execute();
int rsCount = 0;
do {
if(results) {
ResultSet rs = cstmt.getResultSet();
resultset.add(rs);
rsCount++;
System.out.println("RESULT SET #" + rsCount);
// rs.close();
}
System.out.println();
results = cstmt.getMoreResults();
} while(results);
//cstmt.getMoreResults(Statement.KEEP_CURRENT_RESULT);
//cstmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
return resultset;
}
public static void closeDB() throws SQLException
{
connection.close();
}
}
This is my second class Reimbursement class
public class Reimbursement
{
ArrayList<ResultSet> result = DBVerification.executeStoredProcedure("getreimbursements");
for (ResultSet curInstance: result) {
if(result.indexOf(curInstance) == 0)
{
while(curInstance.next())
{
String branchName=curInstance.getString("BranchName");
String department=curInstance.getString("DepartmentName");
String employee=curInstance.getString("EmployeeName");
String title=curInstance.getString("Title");
String claimdate=ValueConverter.DateFormat(curInstance.getString("Date"));
}
curInstance.close();
}
if(result.indexOf(curInstance) == 1)
{
while(curInstance.next())
{
String category=curInstance.getString("Category");
String expensedate=ValueConverter.DateFormat(curInstance.getString("ExpenseDate"));
String description=curInstance.getString("Description");
String approvedby=curInstance.getString("ApprovedBy");
}
curInstance.close();
}
}
DBVerification.closeDB();
}
Please do not look for main method because this is for testing class so i'm already using this class in my xml file.
Please give me suggestion that what i'm doing wrong it give me error message that 'The result set is closed'.
Image of exception actually it is my test class so it will display error only in this form i have edited the line which was indicated
exception message
I think your problem might be as follows
you loop around the response to the call to your stored procedure, adding each result set from the call in to an arraylist
you return the arraylist back to your calling method and iterate over it
you try to process each resultset in turn.
Unfortunately, I think that the action of cstmt.getMoreResults() closes any open result sets before moving to the next one. What you are ending up with is an arraylist of closed ResultSet objects. When you try to read from them, you get the error saying "result set is already closed"
from the java docs
boolean getMoreResults()
throws SQLException
Moves to this Statement object's next result, returns true if it is a
ResultSet object, and implicitly closes any current ResultSet
object(s) obtained with the method getResultSet.

Java Servlet Static DAO

I've have tried to read about using static or not using static in my web application and wanted to just quickly ask if my implementation is good.
The following is my servlet
Integer total = HousingDAO.getTotal(AppUtils.getId(request));
Integer used = HousingDAO.getUsed(AppUtils.getId(request));
request.setAttribute("total", total);
request.setAttribute("used", used);
request.getRequestDispatcher("system/housing.jsp").forward(request, response);
And this is my DAO
public class HousingDAO {
public static Integer getTotal(String id){
String sql_total = "SELECT count(*) FROM housing " +
"WHERE id = :id ";
try (Connection con = ConnectionManager.getSql2o().open()) {
return con.createQuery(sql_total).addParameter("id", id).executeScalar(Integer.class);
}
}
public static Integer getUsed(String id){
String sql_total = "SELECT count(*) FROM housing " +
"WHERE id = :id AND person IS NOT NULL";
try (Connection con = ConnectionManager.getSql2o().open()) {
return con.createQuery(sql_total).addParameter("id", id).executeScalar(Integer.class);
}
}
}
So these are static, does it need to not be static, like this?
HousingDAO dao = new HousingDAO();
Integer total = dao.getTotal(AppUtils.getId(request));
Integer used = dao.getUsed(AppUtils.getId(request));
request.setAttribute("total", total);
request.setAttribute("used", used);
request.getRequestDispatcher("system/housing.jsp").forward(request, response);
With this DAO
public class HousingDAO {
public Integer getTotal(String id){
String sql_total = "SELECT count(*) FROM housing " +
"WHERE id = :id ";
try (Connection con = ConnectionManager.getSql2o().open()) {
return con.createQuery(sql_total).addParameter("id", id).executeScalar(Integer.class);
}
}
public Integer getUsed(String id){
String sql_total = "SELECT count(*) FROM housing " +
"WHERE id = :id AND person IS NOT NULL";
try (Connection con = ConnectionManager.getSql2o().open()) {
return con.createQuery(sql_total).addParameter("id", id).executeScalar(Integer.class);
}
}
}
Just would like to know if the first is ok, or do I need to do it like the second one?
EDIT
This is the ConnectionManager class
public static Sql2o getSql2o(){
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
return new Sql2o(PropertiesManager.getProperty("dburl")
+ PropertiesManager.getProperty("dbname"),
PropertiesManager.getProperty("dbusername"),
PropertiesManager.getProperty("dbpassword"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
There are rarely any good reasons for using static methods. It is most often used in utility classes and classes that in their nature are singletons, like javas System class.
In your case, having a DAO class with static methods is according to me a bad idea. If the methods are static anything they reference has to be static. What if you want to reuse your DAO class to connect to several different databases?
A better approach is to inject all your dependencies in your DAO class, like the static ConnectionManager, and let the application decide how instances are wired together, not the classes themselves.
So the short answer is, use the second solution, but also remove the static access to ConnectionManager.

Convert a parameter according to Database in Java Spring

Here i got value for catname from parameter as movie but in database its have corresponding value as 1, same for music->2, game->3....
"WHERE (\n" +
"\t\t(`Post`.`status` = 1)\n" +
"\t\tAND (`Post`.`postto_id` =\"+catname+\" \")\n" +
"\t\t)" +
"ORDER BY `Post`.`id` desc LIMIT 5", new CrelistMapper());
} catch (Exception e) {
throw e;
}
}
private class CrelistMapper implements ResultSetExtractor<List<Creativity>> {
public List<Creativity> extractData(ResultSet resultSet) throws SQLException {
List<Creativity> crelistList = new ArrayList<Creativity>();
while (resultSet.next()) {
Creativity userObject = new Creativity(resultSet.getString("**postto_id**"),
Here i got value as movie in "postto_id" how can i convert it into 1 instead of movies from parameter?
I believe you are looking for parse int from Integer class.
import java.lang.Integer;
public class test{
public static void main(String[] args){
String stringId = "1";
int intFromString = Integer.parseInt(stringId);
System.out.println(intFromString);
}
}
Look here for a version of the overloaded method that meets your purpose

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