Link to home
Start Free TrialLog in
Avatar of mwhc
mwhc

asked on

How to make this sql processing faster?

Hi,

My code below does this,

-it reads rows from a db table row by row
-every row that is reads it gets the user info and send data to the user info via a method sendText()

Now, my current code takes very long to run especially when there's lots of rows. My requests are,

-Suggestion on how to load my rows of data into memory then send one by one from mem
-Suggestion on improving sql processing of this code.

----CODE--------
/*
 * Classname: FortuneTellerReadingsDelivery.java Description: Generic class to send
 * readings to fortune teller subscribers
 *
 * Author: melwong Date started: 11-Mar-2004
 *
 * Version: 1.0
 */

package com.jm.fortuneteller;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbutils.DbUtils;

import com.jm.config.DbConfig;
import com.jm.config.FileConfig;
import com.jm.config.PropertyFileReader;
import com.jm.gateway.OutboundResponse;
import com.jm.util.KeywordProcessor;

public class FortuneTellerReadingsDelivery {
      
      private Connection conn = null;
      
      //Melvin:16/03/06
      public FortuneTellerReadingsDelivery(Connection conn) {
            this.conn = conn;
            
      }


      public void processDelivery (String message) {
            
            int[] fortuneReadings = null;
            int groupId = 0;
            int serviceId = 0;
            int subkeyword1Id = 0;
            String lineFeed = "";
            String serviceKeyword = "";
            String fortuneCookie = "";
            String readings = "";
            String phoneNumber = "";
            String sqlStr = "";
            
            //Melvin:16/03/06
            //Connection conn = null;
            
            PreparedStatement statement = null;
            ResultSet rs = null;
            KeywordProcessor keyPro = null;
            OutboundResponse outRes = null;
            FortuneTellerUtils util = null;

            keyPro = new KeywordProcessor();
            outRes = new OutboundResponse();
            util = new FortuneTellerUtils();
            
            lineFeed = System.getProperty("line.separator");
            
            //To get the subscribers table
            serviceId = keyPro.getServiceId(message);
            subkeyword1Id = keyPro.getSubkeyword1Id(message, serviceId);
            groupId = keyPro.getGroupId(subkeyword1Id);
            serviceKeyword = keyPro.getServiceKeyword(groupId);
            
            //Melvin:16/03/06
            //Get one fortune cookie for all subscribers
            fortuneCookie = util.getFortuneCookie();

            try {
                  //Melvin:16/03/06
                  //DbUtils.loadDriver(DbConfig.dbDriver);
                  //conn = DriverManager.getConnection(DbConfig.dbUrl);

                  sqlStr = "SELECT DISTINCT phoneNumber FROM "
                              + serviceKeyword + "_fortuneteller_users"
                              + " WHERE inactive = 0";
                  
                  statement = conn
                              .prepareStatement(sqlStr);
                  rs = statement.executeQuery();

                  while (rs.next()) {
                        phoneNumber = rs.getString(1);
                        
                        fortuneReadings = util.getFortuneReadings();
                        
                        //Melvin:16/03/06
                        //fortuneCookie = util.getFortuneCookie();
                        
                        readings = "Love:" + fortuneReadings[0] + "%" + lineFeed
                                          + "Money:" + fortuneReadings[1] + "%" + lineFeed
                                          + "Attitude:" + fortuneReadings[2] + "%";
                        
                        //Melvin: 02/08/05
                        outRes.processText(groupId, "Your today's fortune cookie: " + fortuneCookie + lineFeed + readings, phoneNumber);
                        //outRes.processText(groupId, fortuneCookie + lineFeed + readings, phoneNumber);

                  }

            } catch (SQLException e) {
                  throw new FortuneTellerException(this.getClass().toString(), e);
            } finally{
                  DbUtils.closeQuietly(rs);
                  DbUtils.closeQuietly(statement);
                  
                  //Melvin:16/03/06
                  //DbUtils.closeQuietly(conn);
            }

      }

      
      public static void main(String args[]) {

            String message = "";
            String absPath = "";
            PropertyFileReader readProp = null;
            DbConfig initDbConfig = null;
            FortuneTellerReadingsDelivery fortuneTellerReadingsDelivery = null;
            
            //Melvin:16/03/06
            Connection conn = null;

            if (args.length != 0) {

                  absPath = args[0];

                  for (int i = 1; i < args.length; i++) {
                        message += args[i];
                        message += " ";
                  }
                  message = message.trim();

                  System.out.println("absPath=" + absPath);
                  System.out.println("message=" + message);

            } else {
                  System.err
                              .println("FortuneTellerReadingsDelivery: ERROR: Invalid command line arguments.");
                  System.err.println("\tFortuneTellerReadingsDelivery: Usage:");
                  System.err
                              .println("\tjava FortuneTellerReadingsDelivery <full webapp path> <full SMS message>");
                  System.err
                              .println("\tE.g: java FortuneTellerReadingsDelivery C:\\tomcat\\webapps\\jm HI FC");
                  System.exit(1);
            }

            //Read properties must process first, then initialize db
            readProp = new PropertyFileReader(absPath);
            
            //To initialize the db stuffs
            initDbConfig = new DbConfig();

            //To get URL for WAP Push and app full path
            FileConfig.setSysConfig();
            
            //Melvin:16/03/06
            try {
                  DbUtils.loadDriver(DbConfig.dbDriver);
                  conn = DriverManager.getConnection(DbConfig.dbUrl);
                  fortuneTellerReadingsDelivery = new FortuneTellerReadingsDelivery(conn);
                  fortuneTellerReadingsDelivery.processDelivery(message);
            } catch (SQLException e) {
                  throw new FortuneTellerException("FortuneTellerReadingsDelivery", e);
            } finally {
                  DbUtils.closeQuietly(conn);
            }
            //fortuneTellerReadingsDelivery = new FortuneTellerReadingsDelivery();

            //fortuneTellerReadingsDelivery.processDelivery(message);

      }

}

---EOF CODE-----
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You can start with:

a. bind the parameter to the PS

statement.setString(1, serviceKeyword);

b. make sure there's an index on phone number column


Does the below need to be called in the loop?

>>fortuneReadings = util.getFortuneReadings();
Don't use a PreparedSTatement, just use a standard one using createStatement()

And if your result set size is large then try adjusting the fetch size of the resukt set

Avatar of mwhc
mwhc

ASKER

Hi CEHJ,

a. What is PS

>>Does the below need to be called in the loop?
>>fortuneReadings = util.getFortuneReadings();
Yes is does.

To objects,
How do I adjust the fetch size of the result set?
Avatar of mwhc

ASKER

BTW,

What do you mean by "make sure there's an index on phone number column". This is my table structure,

CREATE TABLE `just_fortuneteller_users` (
  `userId` int(11) NOT NULL auto_increment,
  `phoneNumber` varchar(100) NOT NULL default '',
  `registrationTime` datetime NOT NULL default '0000-00-00 00:00:00',
  `totalMessage` int(11) NOT NULL default '0',
  `inactive` int(11) NOT NULL default '0',
  PRIMARY KEY  (`userId`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Is this ok?

Melv
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
> How do I adjust the fetch size of the result set?

rs.setFetchSize(size);

http://java.sun.com/j2se/1.5.0/docs/api/java/sql/ResultSet.html#setFetchSize(int)
Avatar of mwhc

ASKER

Hi,

I'm learning on indexing now. But I found out that indexing is useful especially in the WHERE statement. Will it be useful in my phoneNumber col since it's not in the WHERE statement?
doubt it, your better off indexing on inactive.
>>But I found out that indexing is useful especially in the WHERE statement.
>>your better off indexing on inactive.

Sorry mwhc, inactive is the correct column