JDBC - How do I accumulate data from ResultSet - jdbc

How would I accumulate data from a ResultSet? What I'm trying to do is get the price from the ResultSet and it only gets the first value, but what I want is every price for e.g 25.0, 10.00, and 15.00 I have stored them in a Double datatype, but the Result Set only gets the last value when I have a while(rs.next() and if I have if(rs.next()) it will get 25.00 but I want all the prices to be added. How would I do this exactly? Thanks!
if(rs2.next()) {
jTextArea3.append("\n");
jTextArea3.append("\n");
jTextArea3.append("Part Type: " + rs2.getString("PartType"));
jTextArea3.append("\n");
jTextArea3.append("Description: " + rs2.getString("Description"));
jTextArea3.append("\n");
jTextArea3.append("Price: " + rs2.getString("Price"));
partsCost = rs2.getDouble("Price");
System.out.println(partsCost);
}

Maybe something like this is what you mean?
double total = 0;
while(rs.next()) {
jTextArea3.append("\n");
jTextArea3.append("\n");
jTextArea3.append("Part Type: " + rs2.getString("PartType"));
jTextArea3.append("\n");
jTextArea3.append("Description: " + rs2.getString("Description"));
jTextArea3.append("\n");
jTextArea3.append("Price: " + rs2.getString("Price"));
partsCost = rs2.getDouble("Price");
System.out.println(partsCost);
total += partsCost;
}
System.out.println(total);
You don't show the SQL query. If you only care about the total of partsCosts, and not the other details, you would need to change your query to have an aggregate function such as, "select sum(partsCost)... "

Related

Alias Column In Resultset

I have a query in backend spring project, where I create a field alias named agent_id but I don´t have that column in Model. What is the best approach for showing this as a field in table view in front end???.
Here´s the query:
Query query = em.createNativeQuery("SELECT" +
" ips.*, " +
" s.mls_id AS imported," +
" p.INTEGRATOR_SALES_ASSOCIATED_ID AS agent_id " +
"FROM test1.ilist_property_summary ips " +
" LEFT JOIN test1.statistics s ON s.mls_id = ips.INTEGRATOR_PROPERTY_ID " +
" LEFT JOIN test1.person p ON p.INTEGRATOR_SALES_ASSOCIATED_ID = ips.INTEGRATOR_SALES_ASSOCIATED_ID " +
"WHERE ips.AGENCY_ID = :agencyId AND (s.statistics_type = 1 OR s.statistics_type IS NULL) AND ips.ORIG_LISTING_DATE BETWEEN :startDate AND :endDate");
query.setParameter("agencyId", agencyId)
.setParameter("startDate", DateUtil.asDate(startDate), TemporalType.DATE)
.setParameter("endDate", DateUtil.asDate(endDate), TemporalType.DATE);
return (List<PropertyVO>) query.getResultList().stream().map(o -> processProperty((Object[]) o)).collect(Collectors.<PropertyVO>toList());
I already have a field that shows agent_id, but not fetched with same field of table Person. I need to retrieve that field agent id alias fetched from left join.
I followed another approach:
Query query = em.createNativeQuery("SELECT" +
" ips.id, ips.agency_id, ips.integrator_property_id, ips.orig_listing_date, ips.contract_type," +
" ips.transaction_type, ips.current_listing_price, ips.current_listing_currency, ips.apartment_number, ips.commercial_residential," +
" ips.commission_percent, ips.commission_value, ips.property_type, ips.street_name, ips.street_number," +
" s.mls_id AS imported," +
" p.INTEGRATOR_SALES_ASSOCIATED_ID AS INTEGRATOR_SALES_ASSOCIATED_ID" +
" FROM test1.ilist_property_summary ips " +
" LEFT JOIN test1.statistics s ON s.mls_id = ips.INTEGRATOR_PROPERTY_ID " +
" LEFT JOIN test1.person p ON p.INTEGRATOR_SALES_ASSOCIATED_ID = ips.INTEGRATOR_SALES_ASSOCIATED_ID " +
"WHERE ips.AGENCY_ID = :agencyId AND (s.statistics_type = 1 OR s.statistics_type IS NULL) AND ips.ORIG_LISTING_DATE BETWEEN :startDate AND :endDate ");
Here field
INTEGRATOR_SALES_ASSOCIATED_ID
is taken from table p, and not from ips. I just selected specific fields so this one could be taken from the other table.

Why query just returns first 100 users?

I want get 40 users where "score" less or equal to some value, and 40 users where "score" greater or equal to the same value. But both queries return just first 100 users which sorted by score in descending order.
Here is some part of code
var query = ParseUser.Query;
if(mode==0)
{
query.WhereNotEqualTo("fbLogged", true)
.WhereNotEqualTo("username", SaveManager.Instance.TempUsername)
.WhereGreaterThanOrEqualTo("score", SaveManager.Instance.Score)
.Limit(40);
}
query.FindAsync().ContinueWith(t =>
{
if (t.IsCanceled || t.IsFaulted)
{
foreach (var e in t.Exception.InnerExceptions)
Debug.LogError("Error: " + e.Message);
return;
}
else
{
var query1 = ParseUser.Query;
if(mode==0)
{
query1.WhereNotEqualTo("fbLogged", true)
.WhereNotEqualTo("username", SaveManager.Instance.TempUsername)
.WhereLessThanOrEqualTo("score", SaveManager.Instance.Score)
.Limit(40);
}
query1.FindAsync().ContinueWith(t1=>
{
Debug.Log("first query count: " + t.Result.ToList().Count);
Debug.Log("second query count: " + t1.Result.ToList().Count);
var r = t.Result.ToList();
r.AddRange(t1.Result.ToList());
List<UserRank> ranks = new List<UserRank>();
r.ForEach(info => { ranks.Add(RetrieveUserRankData((ParseUser)info)); });
ranks = ranks.OrderByDescending(ur => ur.Score).ToList();
UserRank first = ranks.First();
UserRank last = ranks.Last();
Debug.Log("my score: " + SaveManager.Instance.Score);
Debug.Log("first name and score: " + first.Name + " " + first.Score);
Debug.Log("last name and score: " + last.Name + " " + last.Score);
Also here is the log
What did I do wrong?
By default, a query default limit is 100 rows. And the maximum number of rows is 1000. To increase the limit, use query.setLimit(1000) to increase the number of queried row to 1000.

Birt report parameter passing

Hi i have to pass parameter to a report...with a concat-date ....but its showing error...
like this...am having in list box with 2011-2012,2012-2013...here is my oracle query
DATE FOMART IN DATABASE:25-Mar-2012
oracle query
select tran_date,
ROUND (nvl(sum(WALKIN_WITHOUT_CGROUP),0)/ COUNT(*),2)APC
from OUTLET_PAYMODE_REPORT_FACT
Before Open:
var sqld= new String();
yearParam = params["Year"].value;
yearParam = yearParam.split("-");
startYear = yearParam[0];
endYear = yearParam[1];
this.queryText =this.queryText +" where TRAN_DATE between '" + startYear + "01-Mar-' and '" + endYear + "30-Mar-'"+
"group by tran_date"
but am getting error like this.....
org.eclipse.birt.report.data.oda.jdbc.JDBCException: SQL statement does not return a ResultSet object.
SQL error #1:ORA-01861: literal does not match format string
I think, your sql string should be
" where TRAN_DATE between '01-Mar-" + startYear +
"' and '30-Mar-" + endYear + "' " +
"group by tran_date"

Unable to get out of ORA-00907 error

I am getting the missing right paranthesis error. If I remove the comments around iterator.next() statement, its working fine. Unable to figure out whats wrong. There is NO "(" in the data I pass.
String ORACLE_SUM_QUERY = "select item_number, sum(system_quantity) from ITEMS " +
"where sndate = ? and item_id in" +
" (select item_id from ap.system_items where org_id = 4 " +
" and segment1 in ";
......
while (iterator.hasNext()) {
//iterator.next();
String oracleQuery = String.format(ORACLE_SUM_QUERY + "(%s)) GROUP BY item_number", iterator.next());
preparedStat = connection.prepareStatement(oracleQuery);
preparedStat.setDate(1, getSnDate());
The error seems to indicate that the SQL statement you are building up in oracleQuery has an incorrect number of parenthesis. It would probably be helpful to print that SQL statement out before passing it to the prepareStatement call to make debugging easier.
My guess is that the string that is returned by iterator.next() is not what you expect.
Try rewriting your code as
String ORACLE_SUM_QUERY = "select item_number, sum(system_quantity) from ITEMS " +
"where sndate = ? and item_id in" +
" (select item_id from ap.system_items where org_id = 4 " +
" and segment1 in (";
......
while (iterator.hasNext())
{
ORACLE_SUM_QUERY = ORACLE_SUM_QUERY + String.format("%s", iterator.next());
if(iterator.hasNext())
ORACLE_SUM_QUERY = ORACLE_SUM_QUERY + ",";
}
ORACLE_SUM_QUERY = ORACLE_SUM_QUERY + ")) GROUP BY item_number";
preparedStat = connection.prepareStatement(ORACLE_SUM_QUERY);
preparedStat.setDate(1, getSnDate());
This may not get it exactly as I can't test it, but it might get you closer.
Share and enjoy.

Error getting too many character literals

var query = from s in bv.baParticularHeaders
from v in bv.baPlanColumnStructures
where x.Contains(s.Particular_Num)
select new LevelList
{
Value = 'Level ' + LTRIM(Rtrim(Convert(Char,P.Level_Num))) + ' - ',
id = 'Column ' + LTRIM(Rtrim(Convert(Char,P.Column_Num))) + ' ',
Text = v.Column_Description
};
return query.Distinct().OrderBy(o => o.Value).AsQueryable<LevelList>();
Error getting this both lines of code.
Value = 'Level ' + LTRIM(Rtrim(Convert(Char,P.Level_Num))) + ' - ',
id = 'Column ' + LTRIM(Rtrim(Convert(Char,P.Column_Num))) + ' ',
Can any body help me out how to convert this in LINQ?
Thanks
You can't just cut and paste SQL, rearrange it and hope to get a valid LINQ query. The aim is to write the appropriate C# code, which is translated into SQL. In this case I suspect you want:
var query = from s in bv.baParticularHeaders
from v in bv.baPlanColumnStructures
where x.Contains(s.Particular_Num)
select new LevelList
{
Value = "Level " + P.Level_Num + " - ";
id = "Column " + p.Column_Num + " ",
Text = v.Column_Description
};
return query.Distinct().OrderBy(o => o.Value).AsQueryable();
Note the string literals - "Level " not 'Level '. The code has to be valid C# first.
(Assuming Level_Num and Column_Num are numbers, I can't see why it would make sense to trim them.)

Resources