每次调用jdbc都要加载驱动,连接数据库,这样不仅浪费了系统资源,还增加了写代码的难度,所以我们将JDBC连接数据库的部分操作封装到类中,调用类的方法实现数据库的连接;
public class JDBCUtil {
private JDBCUtil() {
}
//静态代码块,只执行一次,保证驱动只加载一次
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws ClassNotFoundException, SQLException {
//Class.forName("com.mysql.jdbc.Driver");//每次调用都要加载驱动,很浪费,写在静态代码块中只加载一次即可
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/java?useUnicode=true&characterEncoding=UTF-8", "root", "");
return connection;
}
public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
if (resultSet != null)
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
if (preparedStatement != null)
try {
preparedStatement.close();
} catch (SQ