一、JDBCUtils工具类
在JDBC中获取连接和释放资源经常使用,可以创建一个工具类。
配置文件
user=root
password=654321
url=jdbc:mysql://localhost:3306/jun_db02
driver=com.mysql.jdbc.Driver
package com.jun.jdbc.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* JDBCUtils工具类
*/
public class JDBCUtils {
//定义属性
private static String user;//用户名
private static String password;//密码
private static String url;//url
private static String driver;//驱动名称
static {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src\\mysql.properites"));
//读取相关属性
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
} catch (IOException e) {
//在实际开发中异常处理
//将编译异常转成运行异常,调用者可以选择捕获或者默认处理,方便了许多
throw new RuntimeException(e);
}
}
//连接数据库,返回Connection
public static Connection getConnection() {
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//关闭相关连接
//有需要关闭的就传入对象,没有就传入null
public static void close(ResultSet resultSet, Statement statement, Connection connection) {
//判断是否传入为null
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
二·、测试工具类
package com.jun.jdbc.utils;
import org.junit.Test;
import java.sql.*;
/**
* 使用工具类测试dml和select
*/
public class JDBCUtils01 {
public static void main(String[] args) {
}
@Test
public void selectTest() {
//得到连接
Connection connection = null;
//sql语句
String sql = "select*from actor";
//创建PreparedStatement对象
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
//执行sql语句
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
Date borndate = resultSet.getDate("borndate");
String phone = resultSet.getString("phone");
System.out.println(id+"\t"+name+"\t"+borndate+"\t"+phone);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭流
JDBCUtils.close(null, preparedStatement, connection);
}
}
@Test
public void testDML() {//insert update,delete
//得到连接
Connection connection = null;
//sql语句
String sql = "update actor set name=? where id=?";
//创建PreparedStatement对象
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
//给?赋值
preparedStatement.setString(1, "lala");
preparedStatement.setInt(2, 1);
//执行sql语句
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭流
JDBCUtils.close(null, preparedStatement, connection);
}
}
}