配置文件内容如下:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///freedom
user=root
password=root
看工具类:
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtils {
private static Properties prop = null;
private JDBCUtils() {
}
static{
try{
prop = new Properties();
prop.load(new FileReader(JDBCUtils.class.getClassLoader().getResource("config.properties").getPath()));
}catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 获取连接
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConn() throws ClassNotFoundException, SQLException{
// 1.注册数据库驱动
Class.forName(prop.getProperty("driver"));
// 2.获取连接
return DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("user"), prop.getProperty("password"));
}
/**
* 关闭连接
*/
public static void close(ResultSet rs, Statement stat,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
rs = null;
}
}
if(stat!=null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
stat = null;
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
conn = null;
}
}
}
}
我们再看使用工具类简化后的操作例子:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
import com.itheima.util.JDBCUtils;
public class FreedomJDBC {
/**
* @Title: add
* @Description: 增加
* @throws
*/
@Test
public void add() {
Connection conn = null;
Statement stat = null;
try {
// 1.注册数据库驱动
// 2.获取连接
conn = JDBCUtils.getConn();
// 3.获取传输器对象
stat = conn.createStatement();
// 4.执行sql语句
int count = stat
.executeUpdate("insert into user values (null,'freedom','123456','freedom@qq.com','2012-01-01')");
// 5.处理结果
if (count > 0) {
System.out.println("执行成功!影响到的行数为" + count);
} else {
System.out.println("执行失败!!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 6.关闭资源
JDBCUtils.close(null, stat, conn);
}
}
/**
* @Title: delete
* @Description:删除
* @throws
*/
@Test
public void delete() {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConn();
stat = conn.createStatement();
stat.executeUpdate("delete from user where name='freedom'");
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stat, conn);
}
}
/**
* @Title: update
* @Description: 更新
* @throws
*/
@Test
public void update() {
Connection conn = null;
Statement stat = null;
try {
conn = JDBCUtils.getConn();
stat = conn.createStatement();
stat
.executeUpdate("update user set password=666 where name='freedom'");
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(null, s