Sunday, January 12, 2014

Read .sql file and replace key in Java


1. Create "Search.sql" file in Java project. Input the below query and then save file.

select s.shipper_number as "SSCC number", 
       it.item_code as "Item code",
       CAST(ia.parameter as INTEGER)/1000 as "Weight (Kg)",
       i.create_time as "Date & time", 
       r.adjust_reason as "Operation", 
       (u.u_first_name||' '||u.u_last_name) as "User name", 
       u.u_username as "Employee Number",
       z.zone_name as "Zone name"
from shippers s, inventory_log i, reason_codes r, users u, locations l, zones z, items it, inventory_attrib ia
where s.shipper_id = i.shipper_id 
      and i.reason_code = r.reason_id 
      and i.user_id = u.u_id 
      and i.location_id = l.location_id
      and l.zone_id = z.zone_id
      and i.item_id = it.item_id
      and i.stock_id = ia.stock_id
      and ia.attribute = 'Weight'
      and s.shipper_number = '@ssccnumber'
order by i.create_time 
2.  Create search() method in Java program.

public void search(){
  String query = null, line = null;
  StringBuilder sb = new StringBuilder();
  
  try{
   FileReader fr = new FileReader(new File("search.sql"));
   BufferedReader bf = new BufferedReader(fr);
   while((line=bf.readLine())!=null){
    sb.append(line);
    sb.append("\n");
   }
  }catch(IOException e){
   e.printStackTrace();
  }
  //_sscreen.getSSCC() is text of JTextField.
  query = sb.toString().replace("@ssccnumber", _sscreen.getSSCC());
  _db.conToRDS();
  _db.setQuery(query);
 }
If you have more than one key word, you can use String.replace(oldChar, newChar).replace(oldChar2, newChar2);




No comments:

Post a Comment