打开类中每个方法的DB连接

时间:2017-09-28 06:23:49

标签: java mysql jdbc

我编写了一个控制器类,其中包含许多执行某些数据库事务的方法。对于每个方法,都会创建DBConnect类的对象。我想知道以下哪种方式更有效。

(1)打开每种方法的连接(如附加代码所示)

(2)为类打开一个连接并在该类的所有方法中使用它 我的代码是:

public class HotelController
{
    Connection conn;
    ResultSet rs;
    PreparedStatement preparedstatement;

    public void addNewHotel( Hotel hotel ) throws Exception
    {
        try
        {
            conn = DBConnect.getInstance().getConnect();
            String sql = "insert into hotel" + " (hotelName,city) values (?,?)";
            preparedstatement = conn.prepareStatement( sql );
            preparedstatement.setString( 1, hotel.getName() );
            preparedstatement.setString( 2, hotel.getCity() );

            boolean flag = preparedstatement.execute();
            if ( flag )
            {
                JOptionPane.showMessageDialog( null, "Hotel Details Added Successfully." );
            }
        }
        catch ( SQLException ex )
        {
            ex.printStackTrace();
        }
    }

    public int getHotelID( String name ) throws Exception
    {
        int id = 1;
        try
        {
            conn = DBConnect.getInstance().getConnect();
            String sql = "select hotelID from hotel where hotelName = ?";
            preparedstatement = conn.prepareStatement( sql );
            preparedstatement.setString( 1, name );
            rs = preparedstatement.executeQuery();

            while ( rs.next() )
            {
                id = rs.getInt( 1 );
            }
        }
        catch ( SQLException ex )
        {
            ex.printStackTrace();
        }
        return id;
    }

    public void loadHotels( JComboBox cbox ) throws Exception
    {
        try
        {
            conn = DBConnect.getInstance().getConnect();
            String sql = "select hotelName from hotel";
            preparedstatement = conn.prepareStatement( sql );
            rs = preparedstatement.executeQuery();

            while ( rs.next() )
            {
                cbox.addItem( rs.getString( "hotelName" ) );
            }
        }
        catch ( SQLException ex )
        {
            ex.printStackTrace();
        }
        finally {

        }
    }

}

1 个答案:

答案 0 :(得分:0)

尝试使用连接池,因为打开/关闭数据库连接是一个昂贵的过程,因此连接池可以提高我们在池中维护连接对象的数据库上命令执行的性能。它有助于重用相同的连接对象来服务于许多客户端请求。每次收到客户端请求时,都会在池中搜索可用的连接对象,并且它很可能获得一个空闲的连接对象。否则,传入的请求将排队或创建新的连接对象并添加到池中。因为大多数请求仅使用现有连接对象提供,因此连接池方法会降低用户等待所需的平均时间建立与数据库的连接。