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);
Related
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;";
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);
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'
Ok so basically I have this code:
resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS");
writeResultSet(resultSet);
private void writeResultSet(ResultSet resultSet) throws SQLException {
System.out.println("jestem w writeresultset");
// resultSet is initialised before the first data set
while (resultSet.next()) {
// it is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g., resultSet.getSTring(2);
String id = resultSet.getString("id");
String user = resultSet.getString("IMIE");
String website = resultSet.getString("NAZWISKO");
String summary = resultSet.getString("ADRES");
String date = resultSet.getString("EMAIL");
String comment = resultSet.getString("TELEFON");
String opisso = resultSet.getString("OPIS");
JTextField myOutput = new JTextField(1600);
myOutput.setText("id w bazie danych to " + id + " imie to " + user
+ " nazwisko to " + website + " adres to " + summary + " email to "
+ date + " teelefon to " + comment + " opis to " + opisso);
add(myOutput);
}
}
What I want to achieve is this:
resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS
where NAZWISKO LIKE " variable );
writeResultSet(resultSet);
I want to search by variable which is already defined, however I'm stuck and have no idea how to do it like that.
Use PreparedStatement:
String nazwisko = ...
String query = "select * from FEEDBACK.COMMENTS where NAZWISKO LIKE ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, nazwisko);
ResultSet rs = pstmt.execute();
while (resultSet.next()) {
//...
}
In case you need to use a wildcard for your LIKE, choose one of these:
nazwisko = nazwisko + "%";
nazwisko = "%" + nazwisko;
nazwisko = "%" + nazwisko + "%";
up , there are alot weird errors with your code:
like cannot find symbol variable con or incompatible type boolean cannot be converted to resultset.
I have tried this: but there is an error when executing
preparedStatement = connect
.prepareStatement("select * from FEEDBACK.COMMENTS where NAZWISKO= ? ; ");
preparedStatement.setString(1, surname3);
while (resultSet.next()) {
String id = resultSet.getString("i
d");
String user = resultSet.getString("IMIE");
String website = resultSet.getString("NAZWISKO");
String summary = resultSet.getString("ADRES");
String date = resultSet.getString("EMAIL");
String comment = resultSet.getString("TELEFON");
String opisso = resultSet.getString("OPIS");
JTextField myOutput = new JTextField(1600);
myOutput.setText("id w bazie danych to " + id + " imie to " + user + " nazwisko to " + website + " adres to " + summary + " email to " + date + " teelefon to " + comment + " opis to " + opisso);
add(myOutput);
}
error:
the query went fine but , the error appears here "while (resultSet.next())"
SEVERE: null
java.lang.NullPointerException
at jdbcexample.Main.readDataBase(Main.java:416)
at jdbcexample.Main$7.mousePressed(Main.java:346)
I am trying to update a table, but it isn't working and giving this sql error.
//Updating Buy Table
Integer stkbid = Integer.parseInt(request.getParameter("stockBid"));
System.out.println("stock buy id : " + stkbid);
//get buy details
PreparedStatement stmtbuy = conn.prepareStatement(
"SELECT \"StockSymbol\", \"Unit\", \"Price\", \"ClearingFee\", \"StampDuty\", \"BrokerFee\"" +
"FROM SPM.\"StockBuy\" WHERE \"StockBuyId\" = '"+ stkbid + "'");
System.out.println("Got stock buy details");
ResultSet rs=stmtbuy.executeQuery();
rs.next();
//String stkcode = rs.getString("StockSymbol");
Integer stkunit = Integer.parseInt(rs.getString("Unit"));
stkunit -= stock.getStockUnit();
Double stkprice = Double.parseDouble(rs.getString("Price"));
Double stkclear = Double.parseDouble(rs.getString("ClearingFee"));
Double stksd = Double.parseDouble(rs.getString("StampDuty"));
Double stkbfee = Double.parseDouble(rs.getString("BrokerFee"));
Double stkval = stkunit * stkprice;
Double stknv = stkval + stkval * (stkclear + stksd + stkbfee);
System.out.println(stknv);
PreparedStatement stmtbuy1 = conn.prepareStatement(
"UPDATE SPM.\"StockBuy\" SET \"Unit\" = " + stkunit + ", \"Value\" = " + stkval + ", \"NetValue\" = " + stknv +
"WHERE \"StockBuyId\" = "+ stkbid);
You are missing a space in before the WHERE clause, which messed up your stknv.
" WHERE \"StockBuyId\" = "+ stkbid);
I think it's an obligation of any poster to remind you that you should use parametrized query. So I shall do the same.
"Please use parametrized query!"
The query that is works has a quote at the end:
" WHERE \"StockBuyId\" = '"+ stkbid + "'");
The one that fails does not
"WHERE \"StockBuyId\" = "+ stkbid);
That might have something to do with it.