首先在src下面创建一个文档,文档的内容是连接时需要用到的各种参数
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/java2304?useSSL=false user=root password=123456
具体封装的内容
/**
* 封装jdbc连接数据和关闭数据库
*/
public class JdbcUtil {
private static String url=null; //设置url属性
private static String user=null; //设置user熟悉
private static String password=null; //设置password熟悉
static { //静态代码块这里的静态代码块的作用调用这个封装时,先获取url user password的参数,为下面的加载做准备
try {
Properties properties = new Properties(); //实例化Properties类
properties.load(new FileInputStream("src/db.properties")); //用IO流读取配置信息的参数
String driver = properties.getProperty("driver"); //获取加载驱动的参数
url = properties.getProperty("url"); //获取url参数
user=properties.getProperty("user"); //获取user参数
password =properties.getProperty("password"); //获取password参数
Class.forName(driver); //加载驱动
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection(){ //创建连接方法
Connection connection=null; //创建connection
try {
connection = DriverManager.getConnection(url,user,password);//建立连接
} catch (SQLException e) {
e.printStackTrace();
}
return connection; //返回连接
}
public static void close(Connection connection){
try {
connection.close(); //关闭connection连接对象
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close( Statement statement, Connection connection){
try {
statement.close(); //关闭statement搬运工
connection.close(); //关闭connection连接
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(ResultSet resultSet,Statement statement,Connection connection){
try {
resultSet.close(); //关闭结果集
statement.close(); //关闭statement搬运工
connection.close(); //关闭connection连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}