我编写了一个 Controller 类,其中包含许多执行某些数据库事务的方法。为 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 {
}
}
}
最佳答案
尝试使用连接池,因为打开/关闭数据库连接是一个昂贵的过程,因此连接池提高了我们在池中维护连接对象的数据库上执行命令的性能。它有助于重用同一连接对象来服务多个客户端请求。每次收到客户端请求时,都会在池中搜索可用的连接对象,并且很可能会获得空闲的连接对象。否则,要么将对传入请求进行排队,要么创建新的连接对象并将其添加到池中。由于大多数请求仅使用现有连接对象提供服务,因此连接池方法降低了用户等待所需的平均时间建立与数据库的连接。
关于java - 为类中的每个方法打开数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46462279/