如何推广结果集查询?

时间:2014-11-27 23:12:57

标签: java sqlite resultset

目前我正在编写一个脚本,该脚本从一个数据库的不同表中读取多个值。每次我发起请求时,我都必须打开一个语句并创建一个新的结果集,这会产生可怕的,重复的代码。什么是推广这个的好方法,如何做到这一点?

我的代码中的一些元素。目前只有一个声明,必须插入结束。我问这个问题的主要原因之一。

public static void main(String[] args) throws Exception
{           
    Connection c = null;
    Statement stmt = null;

    try 
    {
        //set up database connection
        Class.forName("org.sqlite.JDBC");
        c = DriverManager.getConnection("jdbc:sqlite:/nfs/home/mals/p/pu2002/workspace/Database2");
        c.setAutoCommit(false);    
        stmt = c.createStatement();
        //end

        //get task id to work with
        String Task_id = null;
        if(args.length != 0) //if an argument was passed, Task_id will be the first element of the array args (arguments)
        {
            Task_id = args[0];
        }
        else if(args.length == 0) //if no arguments were passed, the highest number in the column id from tasks_task will be selected and set as Task_id
        {
            ResultSet TTask_id = stmt.executeQuery("SELECT max(id) FROM tasks_task");
            int t_id = TTask_id.getInt(1);
            Task_id = String.valueOf(t_id);
            TTask_id.close();
        }
        //end

        //get solution IDs from taks_ids
        ArrayList<Integer> List_solIDs = new ArrayList<Integer>(); //create an empty array list
        ResultSet SSolution_task_id = stmt.executeQuery("SELECT id FROM solutions_solution WHERE task_id ="+Task_id + " AND final = 1;"); //Sqlite3-Ausdruck SELECT..., Task IDs verändern pro Aufgabe - "SELECT * FROM solutions_solution where task_id ="+Task_id +";"
        while (SSolution_task_id.next()) //loops through all elements of SSolution_task_id
        {
                List_solIDs.add(SSolution_task_id.getInt("id")); //adds all elements of the resultset SSolution_task_id to the list List_solIDs 
        }
        SSolution_task_id.close();
        //end




        //get logs according to content type
        int count = List_solIDs.size();
        String log_javaBuilder = null;
        List<String> log_JunitChecker = new ArrayList<String>();

        for (int i = 0; i < count; i++) 
        {
            boolean sol_id_valid = false;
            String solID = String.valueOf(List_solIDs.get(i));

            try 
            {
                ResultSet AAttestation_sol_id = stmt.executeQuery("SELECT * FROM attestation_attestation WHERE solution_id =" +solID+";");
                int Returned = AAttestation_sol_id.getInt("final_grade_id");
            }
            catch(Exception e)
            {
                sol_id_valid = true;
            }

            if(sol_id_valid ==true)
            {
            try
            {   
                ResultSet CCresult_javaBuilder = stmt.executeQuery("SELECT log FROM checker_checkerresult WHERE solution_id = " +solID+ " AND content_type_id = 22;");  //"SELECT id FROM checker_checkerresult where solution_id = " +List_solIDs.get(i)+ ";"
                log_javaBuilder = CCresult_javaBuilder.getString("log");
                CCresult_javaBuilder.close();


                ResultSet CCresult_Junit_checker = stmt.executeQuery("SELECT log FROM checker_checkerresult WHERE solution_id = " +solID+ " AND content_type_id = 24;");

                while (CCresult_Junit_checker.next())
                {
                    log_JunitChecker.add(CCresult_Junit_checker.getString("log"));
                }
                CCresult_Junit_checker.close();
            }

            catch (Exception e)
            {
                log_JunitChecker.add(null);
            }
        //end

欢迎所有类型的潜在改进。

P.S。:尝试使用谷歌搜索。

3 个答案:

答案 0 :(得分:1)

比自己编写泛型方法更好的是使用一些框架总是更好。有许多JPA实现不仅可以解决这个问题,还可以处理多个持久层样板代码。从Here开始JPA。您也可以使用Spring JDBC模板来解决上面提到的问题Spring JDBC Documentation

现在,如果您真的不想要任何框架依赖并快速完成此代码,您可以定义自己的JDBCTemplate类,该类接受查询和参数映射并返回ResultSet。该类可以处理开放连接,查询执行和关闭连接等。

答案 1 :(得分:1)

似乎你想看看使用一些ORM层,例如http://hibernate.org/orm/

您正在寻找的可能是更高级别的层次 从底层的低级JDBC编码类型中抽象出来。

答案 2 :(得分:0)

如果您尝试在方法上使用泛型,该怎么办?这是一个简单的例子,只是为了说明,你必须改进这一切:)

资源:official docs

  public static <T> List<T> getSingleValueList(ResultSet rs, Class<T> clazz, String colName) throws Exception {
    ArrayList<T> list = new ArrayList<T>();
    while (rs.next()) {//loops through all elements of generic list
      list.add((T) rs.getObject(colName)); //adds all elements of the resultset rs to the list
    }
    rs.close();

    return list;
  }

  public static <T> T getSingleValue(ResultSet rs, Class<T> clazz, String colName) throws Exception {
    try {
      if (rs.next()) {//loops through all elements of generic list
        return (T) rs.getObject(colName);
      } else {
        throw new Exception("no value found.");
      }
    } finally {
      rs.close();
    }
  }

  public static void main(String[] args) throws Exception {
    Connection c = null;
    Statement stmt = null;

    try {
      //set up database connection
      Class.forName("org.sqlite.JDBC");
      c = DriverManager.getConnection("jdbc:sqlite:/nfs/home/mals/p/pu2002/workspace/Database2");
      c.setAutoCommit(false);
      stmt = c.createStatement();
    //end

      //get task id to work with
      String Task_id = null;
      if (args.length != 0) //if an argument was passed, Task_id will be the first element of the array args (arguments)
      {
        Task_id = args[0];
      } else if (args.length == 0) //if no arguments were passed, the highest number in the column id from tasks_task will be selected and set as Task_id
      {
        ResultSet TTask_id = stmt.executeQuery("SELECT max(id) FROM tasks_task");
        int t_id = TTask_id.getInt(1);
        Task_id = String.valueOf(t_id);
        TTask_id.close();
      }
    //end

      //get solution IDs from taks_ids
      ResultSet SSolution_task_id = stmt.executeQuery("SELECT id FROM solutions_solution WHERE task_id =" + Task_id + " AND final = 1;"); //Sqlite3-Ausdruck SELECT..., Task IDs verändern pro Aufgabe - "SELECT * FROM solutions_solution where task_id ="+Task_id +";"
      List<Integer> List_solIDs = getSingleValueList(SSolution_task_id, Integer.class, "id"); //create an empty array list
      //end

      //get logs according to content type
      int count = List_solIDs.size();
      String log_javaBuilder = null;
      List<String> log_JunitChecker = new ArrayList<String>();
      List<String> tmplog_JunitChecker;

      for (int i = 0; i < count; i++) {
        boolean sol_id_valid = false;
        String solID = String.valueOf(List_solIDs.get(i));

        try {
          ResultSet AAttestation_sol_id = stmt.executeQuery("SELECT * FROM attestation_attestation WHERE solution_id =" + solID + ";");
          Integer Returned = getSingleValue(AAttestation_sol_id, Integer.class, "final_grade_id");
        } catch (Exception e) {
          sol_id_valid = true;
        }

        if (sol_id_valid == true) {
          try {
            ResultSet CCresult_javaBuilder = stmt.executeQuery("SELECT log FROM checker_checkerresult WHERE solution_id = " + solID + " AND content_type_id = 22;");  //"SELECT id FROM checker_checkerresult where solution_id = " +List_solIDs.get(i)+ ";"
            log_javaBuilder = getSingleValue(CCresult_javaBuilder, String.class, "log");

            ResultSet CCresult_Junit_checker = stmt.executeQuery("SELECT log FROM checker_checkerresult WHERE solution_id = " + solID + " AND content_type_id = 24;");

            tmplog_JunitChecker = getSingleValueList(CCresult_Junit_checker, String.class, "log");
            log_JunitChecker.addAll(tmplog_JunitChecker);
          } catch (Exception e) {
            log_JunitChecker.add(null);
          }
          //end  
        }
      }
    } catch (Exception eeee) {
      //handle it
    }
  }

我希望我能给你一个亮点。

无论如何,几乎所有情况下的框架都有很大的帮助。