我们在使用jdbc时,如果需要获取数据库连接和关闭对象。其操作非常繁琐,我们可以写一个工具类,将获取数据库连接和关闭对象的代码封装起来,方便我们使用
注意: 获取数据库对象时需要传递url,username,passwrod参数,非常麻烦,我们使用properties文件(在src目录下建名为jdbc的资源包),自动读取这些参数,每次获取不同数据库只需要修改这些参数即可。
jdbc.properties文件
url=jdbc:mysql://localhost:3306/em?characterEncoding=utf-8
username=root
password=
driver=com.mysql.jdbc.Driver
JdbcUtil类
package dayone;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class JdbcUtil {
//只有静态的变量才可以在静态代码块和静态方法中使用
private static String url;
private static String username;
private static String password;
private static String driver;
static {//使用静态代码块,保证代码块里面的这些资源在多次获取数据库时只被加载一次
try {
//创建Properties集合
Properties p = new Properties();
//获取src路径下文件方式-->ClassLoader类加载器
ClassLoader classLoader = JdbcUtil.class.getClassLoader();
URL resource = classLoader.getResource("jdbc.properties");
String path = resource.getPath();
p.load(new FileReader(path));//将文件的路径传递进去
url = p.getProperty("url");//获取每一个键值对儿的值
username = p.getProperty("username");
password = p.getProperty("password");
driver = p.getProperty("driver");
Class.forName(driver);//注册驱动
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
Connection connection = null;
try {
//这里直接传参即可
connection = DriverManager.getConnection(url,username,password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
}
//关闭的方法
public static void close(Statement statement,Connection connection){
if(statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
//方法的重载,用来应对不同参数的情况
public static void close(ResultSet resultSet,Statement statement, Connection connection){
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
使用演示
package dayone;
import java.sql.*;
public class Pratice1 {
public static void main(String[] args){
ResultSet resultSet = null;
Statement statement = null;
Connection root = null;
try{
//利用我们封装好的方法获取数据库连接
root = JdbcUtil.getConnection();
statement = root.createStatement();
String sql = "select * from employees";
resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.print(resultSet.getInt(1)+" "+resultSet.getString(2)+" ");
System.out.println(resultSet.getInt(3)+" "+resultSet.getInt(4));
}
} catch (SQLException e){
e.printStackTrace();
} finally {
//利用我们封装好的方法进行关闭
JdbcUtil.close(resultSet,statement,root);
}
}
}