use COUNT(*) to count multiple rows from multiple tables in netbean - java

So I want to count the total number of sales for each seller from two different tables.
And I wrote down the code but it does not work..... Can anyone please help me???
So it should produce that sellerID =1 and count = 13. sellerID=2 and count= 14. Something like this. So I want to produce 3 total amount of sales for each seller, but the output shows the red lines ....
String[] sellerID = {"1","2","3"};
int num = 0;
String []totalAmountSale = new String[3];
String sql = "SELECT tblOrder.SellerID, COUNT(*) " +
"FROM tblOrder, tblSeller " +
"WHERE tblOrder.SellerID = tblSeller.SellerID " +
"GROUP BY tblOrder.SellerID"
+ "ORDER BY tblOrder.SellerID;";
ResultSet rs = db.query(sql);
try {
while(rs.next())
{
totalAmountSale[num]= ""+rs.getInt(2);
num++;
}
rs.close();
} catch (SQLException ex) {
Logger.getLogger(DatabaseWork.class.getName()).log(Level.SEVERE, null, ex);
}
String out = "";
for (int i = 0; i < 3; i++) {
out+= totalAmountSale[i]+"\n";
}
JOptionPane.showMessageDialog(null,out );
}

You miss a space:
String sql = "SELECT tblOrder.SellerID, COUNT(*) " +
"FROM tblOrder, tblSeller " +
"WHERE tblOrder.SellerID = tblSeller.SellerID " +
"GROUP BY tblOrder.SellerID "
+ "ORDER BY tblOrder.SellerID;";

Related

Why I keep getting the error : org.postgresql.util.PSQLException: ERROR: syntax error at or near "(" in my jdbc code?

I am trying to write a method in jdbc in order to update some columns in my database (postgresql)
Here is what I have written so far:`
public void showRoomBookings(int clientID) {
Scanner myObj = new Scanner(System.in);
Statement st;
try {
st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet res = st.executeQuery("SELECT rb.\"hotelbookingID\",rb.\"roomID\",rb.\"bookedforpersonID\",rb.checkin,rb.checkout,rb.rate\r\n"
+ "FROM roombooking rb ,hotelbooking hb\r\n"
+ "where rb.\"bookedforpersonID\"=hb.\"bookedbyclientID\"\r\n"
+ "AND hb.\"bookedbyclientID\"="+clientID+"\r\n"
+ "order by rb.\"hotelbookingID\"");
int j=1;
while(res.next()) {
System.out.println(j+")roomID:"+res.getInt(2)
+" bookedforpersonID:"+res.getInt(3)+" checkin:"+res.getDate(4)+" checkout:"+res.getDate(5)
+" rate:"+res.getInt(6));
j++;
}
System.out.println("Enter the number of the room you want to update:");
int answer = myObj.nextInt();
ResultSet res1 = st.executeQuery("Select t2.\"hotelbookingID\",t2.\"roomID\",t2.\"bookedforpersonID\",t2.checkin,t2.checkout,t2.rate\r\n"
+ "From \r\n"
+ "(\r\n"
+ " Select \r\n"
+ " Row_Number() Over (Order By t1.\"hotelbookingID\") As RowNum\r\n"
+ " , *\r\n"
+ " From (\r\n"
+ "SELECT rb.\"hotelbookingID\",rb.\"roomID\",rb.\"bookedforpersonID\",rb.checkin,rb.checkout,rb.rate\r\n"
+ "FROM roombooking rb ,hotelbooking hb\r\n"
+ "where rb.\"bookedforpersonID\"=hb.\"bookedbyclientID\"\r\n"
+ "AND hb.\"bookedbyclientID\"=107\r\n"
+ "order by rb.\"hotelbookingID\"\r\n"
+ " )t1\r\n"
+ ") t2\r\n"
+ "Where RowNum = "+answer);
System.out.println("You chose room: ("+answer+")");
while(res1.next()) {
System.out.println(res1.getInt(1)+" roomID:"+res1.getInt(2)
+" bookedforpersonID:"+res1.getInt(3)+" checkin:"+res1.getDate(4)+" checkout:"+res1.getDate(5)
+" rate:"+res1.getInt(6));
res1.updateInt("rate", 40);
res1.updateRow();
}
res.close();
res1.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
In the first ResultSet res I just project the roombookings bases on the clientID and then with ResultSet res1 I choose one of them. My console looks like this:
The problem here is that when I try to update rate :
res1.updateInt("rate", 40);
res1.updateRow();
I get the following message:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "("
Position: 8 at
postgresql#42.2.20.jre7/org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2553)
at
postgresql#42.2.20.jre7/org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2285)
at
postgresql#42.2.20.jre7/org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:323)
at
postgresql#42.2.20.jre7/org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:481)
at
postgresql#42.2.20.jre7/org.postgresql.jdbc.PgStatement.execute(PgStatement.java:401)
at
postgresql#42.2.20.jre7/org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:164)
at
postgresql#42.2.20.jre7/org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:130)
at
postgresql#42.2.20.jre7/org.postgresql.jdbc.PgResultSet.updateRow(PgResultSet.java:1445)
at lol.DbApp.showRoomBookingss(DbApp.java:246) at
lol.DbApp.main(DbApp.java:290)
Here is my postgresql final result(the same as the last line from the console above):
EDIT: SQL CODE:
Select
t2."hotelbookingID",
t2."roomID",
t2."bookedforpersonID",
t2.checkin,
t2.checkout,
t2.rate
From(
Select
Row_Number() Over (
Order By
t1."hotelbookingID"
) As RowNum,
*
From
(
SELECT
rb."hotelbookingID",
rb."roomID",
rb."bookedforpersonID",
rb.checkin,
rb.checkout,
rb.rate
FROM
roombooking rb,
hotelbooking hb
WHERE
rb."bookedforpersonID" = hb."bookedbyclientID"
AND hb."bookedbyclientID" = 107
order by
rb."hotelbookingID"
) t1
) t2
Where
RowNum = 3
group by
t2."hotelbookingID",
t2."roomID",
t2."bookedforpersonID",
t2.checkin,
t2.checkout,
t2.rate
Any help would be valuable.

For loop inside SQL Create Table query

I am trying to Create a table Model (i, y1, y2 .... yd) in Vertica using JAVA. Column i is integer and all others are REAL. I used the following code to create it. However it is showing syntax error at or near null. Does anybody know what that means? The connection works for the program.
public void createMODEL(int d)
{
int x;
try
{
Statement stmt = conn.createStatement();
String createquery = "CREATE TABLE MODEL ( "
+ "i integer primary key ";
for (x=1;x<=d;x++) createquery+= " , " + Y[x] + " REAL ";
createquery += ")";
stmt.executeUpdate(createquery);
}
catch (Exception e)
{
System.out.println("Error while executing create model query");
System.out.print(e);
System.exit(0);
}
}
Y is defined as follows -
String Y[]=new String[100];
I guess you should check if Y[x] is not null:
Statement stmt = conn.createStatement();
String createquery = "CREATE TABLE MODEL ( "
+ "i integer primary key ";
for (x=1;x<=d;x++) {
if (Y[x] != null) createquery+= " , " + Y[x] + " REAL ";
}
createquery += ")";
stmt.executeUpdate(createquery);
This works for me for MySQL. Try this.
String Y[] = new String[100];
Y[0] = "h";
Y[1] = "ha";
Y[2] = "hat";
Y[3] = "hati";
Y[4] = "hatim";
System.out.println("Your columns array : " + Arrays.deepToString(Y));
String createquery = "CREATE TABLE MODEL ( " + "i integer primary key ";
for (int i = 0; i < Y.length; i++) {
if (Y[i] != null)
createquery += " , " + Y[i] + " REAL ";
}
createquery += ");";
System.out.println("Your create query : " + createquery);

JDBC incorrect syntax at or near "." executeQuery

This is of course parts of a larger code. It will compile with no problem, but when I call this method I get the error
"syntax error near or at "."" at the position of stmt.executeQuery(SQL).
I would really appreciate the help!
private void Component() {
try {
Statement stmt = con.createStatement();
String SQL = "SELECT component.*, stock.amount_of_component, component.price component.component_type "
+ "FROM component JOIN stock "
+ "ON component.id = stock.component_id "
+ "ORDER BY component.component_type";
ResultSet rs = stmt.executeQuery(SQL);
rs.next();
int id = rs.getInt("ID");
int amount_of_component = rs.getInt("Amount");
String name = rs.getString("Name");
double price = rs.getDouble("Price");
String component_type = rs.getString("Type");
System.out.println(" " + id + amount_of_component + " " + name + " " + price + " " + component_type);
} catch (SQLException err)
{
System.out.println(err.getMessage());
}
}
Typo, missing a comma in the query between component.price and component.component_type :
SELECT component.*, stock.amount_of_component, component.price, component.component_type
FROM component JOIN stock
ON component.id = stock.component_id
ORDER BY component.component_type
Edit: To read the whole result set, put this cycle instead of rs.next()
while(result.next()) {
int id = rs.getInt("ID");
int amount_of_component = rs.getInt("Amount");
String name = rs.getString("Name");
double price = rs.getDouble("Price");
String component_type = rs.getString("Type");
System.out.println(" " + id + amount_of_component + " " + name + " " + price + " " + component_type);
}
Edit2: To print the header, you have to do it manually by putting a System.out.println(" id amount_of_component name price component_type "); before the while.
You missed a comma between 'component.price' and 'component.component_type'

Java and sql loop optimization

I'm grabbing a ResultSet from a database of people and ordering them by last names. I also have a table of other people that relate to that other table but since I can't figure out a way to order the second table by the order of ids in the first, I'm forced to execute a statement referring to the current id each time in the loop.
I'm positive the sql statement being executed in the loop through each iteration is what's slowing things down.
Slow code with reoccurring sql statement in loop
startTime = System.nanoTime();
int id;
String phone;
for (int i = 0; i < studentCount; i++) {
rs.next();
String name;
id = Integer.parseInt(rs.getString(1));
String middleInitial = rs.getString(3);
if (middleInitial == null){
name = rs.getString(2) + " " + rs.getString(4);
}
else
name = rs.getString(2) + " " + middleInitial + " " + rs.getString(4);
sql = "select parent1mobilephone, parent1workphone from tblParent where id = " + id;
rs2 = st2.executeQuery(sql);
rs2.next();
phone = rs2.getString(1).length() == 12 ? rs2.getString(1) : rs2.getString(2);
rs2.close();
DirectoryBoxesPanel.add(new DirectoryBoxes(name, id, phone, selection));
}
endTime = System.nanoTime();
duration = (endTime - startTime);
System.out.println("For LOOP: " + duration/1000000L);
Faster unfinished code
startTime = System.nanoTime();
int id;
String phone;
sql = "select parent1mobilephone, parent1workphone from tblParent ORDER by FIRST TABLE";
rs2 = st2.executeQuery(sql);
for (int i = 0; i < studentCount; i++) {
rs.next();
String name;
id = Integer.parseInt(rs.getString(1));
String middleInitial = rs.getString(3);
if (middleInitial == null){
name = rs.getString(2) + " " + rs.getString(4);
}
else
name = rs.getString(2) + " " + middleInitial + " " + rs.getString(4);
rs2.next();
phone = rs2.getString(1).length() == 12 ? rs2.getString(1) : rs2.getString(2);
DirectoryBoxesPanel.add(new DirectoryBoxes(name, id, phone, selection));
}
endTime = System.nanoTime();
duration = (endTime - startTime);
System.out.println("For LOOP: " + duration/1000000L);
The only other way I can think of making this faster would be putting the two tables together in one but I don't know if I want to resort to that yet.
I am assuming that your ResultSet rs is based on a SQL statement that goes like this (fully groping in the dark here due to total lack of detail in the question):
sql = "select id, first_name, middle_initial, last_name from tblStudents";
Your code would become MUCH faster if you retrieve the details from tblParent in that same query, like (again, going blind on the table structure):
sql = "select s.id, s.first_name, s.middle_initial, s.last_name " +
" p.parent1mobilephone, parent1workphone " +
"from tblStudents s join tblParents p on p.student_id = s.id " +
"order by s.last_name";
Your Java code then becomes a simple loop over the ResultSet:
startTime = System.nanoTime();
rs = ...;
while rs.next() {
integer id = rs.getInt(1));
String middleInitial = rs.getString(3);
if (middleInitial == null) {
String name = rs.getString(2) + " " + rs.getString(4);
} else {
String name = rs.getString(2) + " " + middleInitial + " " + rs.getString(4);
}
String phone = rs.getString(5).length() == 12 ? rs.getString(5) : rs.getString(6);
DirectoryBoxesPanel.add(new DirectoryBoxes(name, id, phone, selection));
}
endTime = System.nanoTime();
duration = (endTime - startTime);
System.out.println("For LOOP: " + duration/1000000L);

Like search not fetching all matching records

I wanted to do multitable search.I have a database in MS Access with 4 tables.So I made 1 more table Index1 which contains the field from all the 4 tables that the user will search.(sort of index/master table). The problem is that the search is not displaying as many records as ideally it should,It displays only few of them. Kindly enlighten me by finding the bug in my code. Thanks in advance !
My code:
//package searchbook;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
public class SearchBook extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession(true);
List booklist = new ArrayList();
Connection con = null;
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\executive_db.accdb";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String user = "";
String pass = "";
String category = "";
category = request.getParameter("input");
String sqlquery = "select Index1.link_id "
+ "FROM Index1 "
+ " WHERE Index1.index_name LIKE '%" + category + "%' ";
String sqlResult = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, pass);
try {
Statement st = con.createStatement();
System.out.println("Connection created 1");
ResultSet rs = st.executeQuery(sqlquery);
while (rs.next()) {
sqlResult = rs.getString(1);
}
System.out.println("Result retreived 1");
//System.out.println('"sqlquery"');
} catch (SQLException s) {
System.out.println("SQL statement is not executed! " + s);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("************");
String sqlq = "";
int flag = 0;
/*if(sqlResult.equals("1"))
{
flag=1;
System.out.println("entered if block for section!");
sqlq="select Report.Report_Name,Report.Report_ID,Report.Section_ID,Report.Contact_ID,Report.link_id FROM Report "
+ " where Report.Report_Name LIKE '%"+category+"%' ";
sqlq="select Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name "
+ "FROM Section , Report , Contact"
+ " WHERE Report.Section_ID=Section.Section_ID and Contact.Contact_ID=Report.Report_ID "
+ "and Section.Section_Name = '"+category+"' ";
} */
if (sqlResult.equals("1")) {
flag = 1;
System.out.println("entered if block for section!");
/*sqlq="select Report.Report_Name,Report.Report_ID,Report.Section_ID,Report.Contact_ID,Report.link_id FROM Report "
+ " where Report.Report_Name LIKE '%"+category+"%' ";*/
sqlq = "select distinct Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name "
+ "FROM Section , Report , Contact"
+ " WHERE Report.Section_ID=Section.Section_ID and Contact.Contact_ID=Report.Contact_ID and Section.Section_Name LIKE '%" + category + "%' ";
// + "and Section.Section_Name = '"+category+"' ";
}
if (sqlResult.equals("2")) {
flag = 1;
System.out.println("entered if block for report!");
/*sqlq="select Report.Report_Name,Report.Report_ID,Report.Section_ID,Report.Contact_ID,Report.link_id FROM Report "
+ " where Report.Report_Name LIKE '%"+category+"%' ";*/
sqlq = "select distinct Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name "
+ "FROM Section , Report , Contact"
+ " WHERE Report.Section_ID=Section.Section_ID and Contact.Contact_ID=Report.Contact_ID and Report.Report_Name LIKE '%" + category + "%' ";
// + "and Report.Report_Name = '"+category+"' ";
}
if (sqlResult.equals("3")) {
flag = 1;
System.out.println("entered if block for metrics !");
/*sqlq="select Report.Report_Name,Report.Report_ID,Report.Section_ID,Report.Contact_ID,Report.link_id FROM Report "
+ " where Report.Report_Name LIKE '%"+category+"%' "*/
;
sqlq = "select distinct Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name "
+ "FROM Section , Report , Contact,Metrics"
+ " WHERE Report.Section_ID=Section.Section_ID and Contact.Contact_ID=Report.Contact_ID and Metrics.Report_ID=Report.Report_ID "
+ "and Metrics.Metric_Name LIKE '%" + category + "%' ";
}
if (sqlResult.equals("4")) {
flag = 1;
System.out.println("entered if block for contact name!");
/*sqlq="select Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name, Metrics.Metric_Name "
+ "FROM Section , Report , Contact, Metrics"
+ " WHERE Report.Section_ID=Section.Section_ID and Metrics.Report_ID=Report.Report_ID "
+ "and Report.Report_ID IN (SELECT Report.Report_ID FROM Report WHERE "
+ "Contact.Contact_ID=Report.Contact_ID and Contact.Contact_Name LIKE '%"+category+"%' and Metrics.Metric_Segment = 'M') ORDER BY Report_Name ";*/
sqlq = "select distinct Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name "
+ "FROM Section , Report , Contact"
+ " WHERE Report.Section_ID=Section.Section_ID and Contact.Contact_ID=Report.Contact_ID "
+ "and Contact.Contact_Name LIKE '%" + category + "%' ";
}
if (flag == 1) {
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, pass);
try {
Statement st = con.createStatement();
System.out.println("Connection created");
ResultSet rs = st.executeQuery(sqlq);
System.out.println("Result retreived for 2nd query ");
while (rs.next()) {
List<String> book = new ArrayList<String>();
String Name = rs.getString("Section_Name");
String reportName = rs.getString("Report_Name");
String link = rs.getString("Link");
String contactName = rs.getString("Contact_Name");
/* String metricName=rs.getString("Metric_Name");*/
//String reportId=rs.getString("Report_ID");
book.add(Name);
book.add(reportName);
book.add(link);
book.add(contactName);
/* book.add(metricName);*/
//book.add(reportId);
/* book.add(ind_id);
book.add(ind_name);*/
booklist.add(book);
}
} catch (SQLException s) {
s.printStackTrace();
System.out.println("SQL statement is not executed in 2nd query! " + s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("And it came here lastly !");
request.setAttribute("booklist", booklist);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/searchbook.jsp");
dispatcher.forward(request, response);
System.out.println("***************************************************************************************");
}
}
Check your logic again. In this loop
while (rs.next()) {
sqlResult = rs.getString(1);
}
you are looping through the first ResultSet, repeatedly assigning
sqlResult = rs.getString(1);
and then doing nothing with it until you hit the end of that while loop, after which you proceed to do some other stuff with the last row fetched by that first query.
Access works different. Use "*" instead of "%" for the like.

Categories