从网站上的PostgreSQL数据库读取的有效方法

时间:2014-11-03 18:46:19

标签: java postgresql jdbc database-connection vaadin

我有2个实体的数据库:商店,产品。每个产品都有他的描述和商店ID的一些专栏,你可以把它作为FK。商店也有一些描述栏目。

我想要TreeTable商店列表。当你在每个商店下扩展树时,你会得到这个商店的产品清单。

正如我所说,我使用Vaadin TreeTable,JDBC驱动程序连接PostgreSQL数据库。

选择商店(约900行)非常快。不到1秒。然而,打开声明,选择每个商店的所有产品并关闭它会杀死我的数据库。

即使我在一家商店购买了1件商品,页面也会加载7-11秒。因此,我猜测开始和结束语是一个主要问题。

编辑:常见的情况是,在一个商店里只有1-2个产品。不再。

我已经发布了我在5个步骤中所做的事情,但是如果你需要rly代码,我会发布一些部分 这是JDBC的常见用法,但是我想问一下如果我需要获取很多行,或者网站被许多用户使用。使用JDBC使其更快的最佳实践是什么。

我的代码:

打开连接:

//in db helper class

Connection conn = null;

void openConnection(){
     static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
     static final String DB_URL = "jdbc:mysql://localhost/shops";
     static final String USER = "username";
     static final String PASS = "password";

     try{
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
     }catch(SQLException se){
        se.printStackTrace();
     }catch(Exception e){
        e.printStackTrace();
     }
 }

 List<Shop> getAllShops(){
     Statement stmt = null;
     try{
       stmt = conn.createStatement();
       ResultSet rs = stmt.executeQuery(sql);
       while(rs.next()){
           //save rs into Shop object
       }
       rs.close();
     }catch(SQLException se){
         se.printStackTrace();
     }finally{
     try{
        if(stmt!=null)
           conn.close();
        }catch(SQLException se){
     }
  }

 //method to get operations is exacly the same but im passing Shop int id into method

  void closeConnection(){
       if(connection != null)
           conn.close();
  }

  //in some layout class
  void createAndFillTableMethod(){
     //create table

      DatabaseHelper db = new DatabaseHelper();
      List<Shop> ls = new ArrayList<Shop>();
      ls = getAllShops();

      for(Shop shop: ls){
          List<Product> lp = new ArrayList<Product>();
          lp = getAllProducts(shop.id);

          //add shop to table
          //add lp list as a childs of shop to table
      }
      db.closeConnection();
 }

ps:我可以跳过一些尝试捕获。

1 个答案:

答案 0 :(得分:1)

问题解决了。当我通过网站连接到数据库时,我发现了一些好习惯。

我做了什么:

  1. 向我的Vaadin Servlet添加了会话事件。
  2. 在会话开始时:打开与PostgreSQL数据库的连接。
  3. 会话结束时:关闭已打开的连接。
  4. 更重要的是:

    为了防止多个打开的连接(通过F5按钮刷新),我用synchronized语句包围一个打开的连接并添加一个标志。

    语句和结果集怎么样:

    这些保持不变。执行并保存结果后,在每次选择和关闭之前打开。

相关问题