简体   繁体   English

使该程序更有效?

[英]Make this program more efficient?

just curious if anyone has any idea for making this program more simple. 只是好奇是否有人有任何想法可以使该程序更简单。 It reads records from a database into an ArrayList and allows the user to search for records by state. 它将记录从数据库读取到ArrayList中,并允许用户按状态搜索记录。 It processes a database of 1 million records in aprox 16000ms. 它处理大约16000毫秒内的100万条记录的数据库。

import java.sql.*;
import java.util.*;
public class ShowEmployeeDB
{
public static void main(String args[])     
{
   ArrayList <String> Recs = new ArrayList <String>();
   String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
   String connectionURL = "jdbc:odbc:CitizensDB";  
   Connection con = null;    
   Statement  stmt = null;     
   String sqlStatement = "SELECT * FROM Citizens";
   ResultSet rs = null;       
   int r = 0;
   Scanner scan = new Scanner(System.in);
   String search = null;
   long starttime = System.currentTimeMillis();
   try 
   {   
       Class.forName(driverName).newInstance();  
       con = DriverManager.getConnection(connectionURL);
       stmt = con.createStatement();    
       rs = stmt.executeQuery(sqlStatement);  

       String ID = null;
       String Age = null;
       String State = null;
       String Gender = null;
       String Status = null;
       String record = null;
       while (rs.next())
       {
           for (int k = 1; k <= 1; ++k)
           {
               ID = rs.getString(k) + " ";
               for (int j = 2; j <= 2; ++j)
                   Age = rs.getString(j) + " ";
               for (int i = 3; i <= 3; ++i)
                   State = rs.getString(i).toUpperCase() + " ";
               for (int h = 4; h <= 4; ++h)
                   Gender = rs.getString(h) + " ";
               for (int g = 5; g <= 5; ++g)
                   Status = rs.getString(g) + " ";
           }//for
           record = ID + Age + State + Gender + Status;
           Recs.add(record);
           ++r;
       }//while
       rs.close();
       stmt.close();
       con.close();
   } catch (Exception ex) { ex.printStackTrace();  }

   String endtime = System.currentTimeMillis() - starttime + "ms";
   System.out.println(endtime);

   System.out.print("Enter A Search State: ");
   search = scan.nextLine().toUpperCase();

   Iterator<String> iter = Recs.iterator();
    while(iter.hasNext())
    {
        String s = iter.next();
        if (s.contains(search))
        {
            System.out.println(s);
        }
    }//while
} // main
} // ShowEmployeeBD

Any advice would be greatly appreciated. 任何建议将不胜感激。 Thank you in advance! 先感谢您!

If search is not often, I would suggest to take the search string input before running the query, so that search results are directly from the DB. 如果不经常搜索,我建议在运行查询之前接受搜索字符串输入,以便搜索结果直接来自数据库。 I this case you do not have to reiterate all 1 million records. 在这种情况下,您不必重复所有的100万条记录。

Perform searching directly on DB rather than fetching all the records and searching through java code. 直接在数据库上执行搜索,而不是获取所有记录并通过Java代码搜索。 Also if search is on multiple column, then prepare a meta data in DB at a single place on the basis of IDs, and the meta data can further be used for fetching the required results that match the query. 同样,如果搜索是在多列上,则根据ID在单个位置的DB中准备一个元数据,然后该元数据可以进一步用于获取与查询匹配的所需结果。

  • Separate your logic from the technical stuff. 将逻辑与技术隔离。 In such a convolut it is difficult to run unit tests or any optimizations. 在这种复杂的情况下,很难进行单元测试或任何优化。
  • Why do you need for loops, when only asking one value. 当只询问一个值时,为什么需要循环。
  • Use StringBuilder instead of String concatenation. 使用StringBuilder代替String串联。
  • Use either try-with or put your close statements in a finally clause. 使用try-with或将close语句放在finally子句中。
  • Don't initialize variables you don't need (r). 不要初始化不需要的变量(r)。
  • Use for each statements. 用于每个语句。
  • Query the database, not the result set. 查询数据库,而不是结果集。
  • Tune your database. 调整数据库。
  • If you are only searching for a state, filter only those, so build an object and compare the state instead of a string contains. 如果仅搜索状态,则仅过滤那些状态,因此构建一个对象并比较状态而不是包含的字符串。
  • Compare the state before storing strings in the list. 在将字符串存储在列表中之前先比较状态。
  • Tune your list because it constantly grows with 1Mio records. 调整您的列表,因为它会随着1Mio记录而不断增长。
  • Use a hashset instead of an arraylist. 使用哈希集而不是arraylist。
  • Develop against interfaces. 针对界面进行开发。

A better program might look like following: 更好的程序可能如下所示:

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class ShowEmployeeDB {

  private static final String DRIVERNAME = "sun.jdbc.odbc.JdbcOdbcDriver";
  private static final String CONNECTIONURL = "jdbc:odbc:CitizensDB";

  private static final String SELECT_CITIZENS = "SELECT * FROM Citizens";

  static {
    try {
      DriverManager.registerDriver((Driver) Class.forName(DRIVERNAME).newInstance());
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
      e.printStackTrace();
    }
  }

  public static void main(final String args[]) {
    System.out.print("Enter A Search State: ");
    searchRecords();
  }

  private static void searchRecords() {
    try(Scanner scan = new Scanner(System.in);) {
      final String state = scan.nextLine();

      final long starttime = System.currentTimeMillis();
      final Set<Record> records = searchRecordsByState(state);
      System.out.println(System.currentTimeMillis() - starttime + "ms");

      for(final Record r : records) {
         System.out.println(r);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static Set<Record> searchRecordsByState(final String stateToFilter) {
    final Set<Record> records = new HashSet<>();
    try(Connection con = DriverManager.getConnection(CONNECTIONURL);
        PreparedStatement stmt = con.prepareStatement(SELECT_CITIZENS);
        ResultSet rs = stmt.executeQuery(); ) {

      while(rs.next()) {
        final String state = rs.getString(3);
        if(state.equalsIgnoreCase(stateToFilter)) {
          final Record r = new Record(rs.getString(1), rs.getString(2), state, rs.getString(4), rs.getString(5));
          records.add(r);
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return records;
  }
}

class Record {
  String id, age, state, gender, status;

  public Record(String id, String age, String state, String gender, String status) {
    this.id = id;
    this.age = age;
    this.state = state;
    this.gender = gender;
    this.status = status;
  }

  public String getState() {
    return state;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append(id).append(' ')
      .append(age).append(' ')
      .append(state).append(' ')
      .append(gender).append(' ')
      .append(status);
    return sb.toString();
  }
}

This is untested, because I don't have a database with a million entries by hand. 这未经测试,因为我没有手工记录一百万个条目的数据库。

But the best would be to query the database and catch only those entries you need. 但是最好的办法是查询数据库并仅捕获您需要的那些条目。 So use the WHERE -clause in your statement. 因此,在您的陈述中使用WHERE- WHERE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM