/** * 数据库工具类,封装数据库操作中多次使用的数据库操作代码 * @author Administrator * */ public class DBUtils { public static Connection getConnection() { Connection connection = null; try { Class.forName("com.mysql.jdbc.Driver"); String databaseName = "jdbc_test"; String url = "jdbc:mysql://localhost:3306/" + databaseName; String user = "root"; String password = "111"; connection = DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return connection; } }
*Connection connection = DBUtils.getConnection();
*PreparedStatement preparedStatement = connection.prepareStatement(sql);
*ResultSet resultSet = preparedStatement.executeQuery();
以上三个流都需要进行关闭 也都可以用try - with - resource 进行关闭 (自动关闭 不需要手动)
时间: 2024-10-13 07:28:50