JBDC
1. 代码优化
步骤:
- 使用DriverManager 进行加载驱动Driver
- 利用加载驱动拿到Connection连接对象
- 通过Connection对象拿到Statement
- 使用Statement对象,进行SQL查询
- 查询返回jieg
- 关闭资源
【优化概括】
利用try/catch,封装进行优化
将相关代码段进行封装,使得当连接数据库改变时,操作简单
public class JDBCUtil {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/test";
private static String user = "root";
private static String password = "123456";
private static Connection conn = null;
private static Statement st = null;
private static ResultSet rs = null;
//刚开始就加载,静态加载,且只执行一次
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//connection获取连接对象
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
//资源关闭(尽晚连接对象,尽早释放对象)
//mysql的连接资源 比较珍稀的资源【先关再开】
public static void jdbcClose(Connection conn,Statement st,ResultSet rs){
try {
rs.close();
if(rs != null) {
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
st.close();
if(st != null){
st = null;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
conn.close();
if(conn != null){
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
注意:
- 最后关闭资源时,先关闭,在赋空
2. 增加添加,修改,删除功能
【封装update】
public void update(String sql){
/*1.日常连接数据库操作
2.在该封装类中调用executeUpdate
*/
try {
conn = JDBCUtil.getConnection();
st = conn.createStatement();
int i = st.executeUpdate(sql);
System.out.println(i);
} catch (SQLException e) {
e.printStackTrace();
}finally {
//使用自己的封装【此处应该要在外面重新写一个只有两个元素的资源关闭】
JDBCUtil.jdbcClose(conn,st);
}
}
【由于增加功能所要增加的资源关闭】
//在进行增删查改时所要关闭的资源
public static void jdbcClose(Connection con,Statement st){
try {
st.close();
if(st != null){
st = null;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
con.close();
if(con != null){
con =null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
3. 单元测试
3.1 步骤:
1.找到想要测试的方法,单击右键,做出如下选择
2.选择
3.如下
4. 新出现输入框中即可进行单元测试
3.2 Update单元测试
public class JDBCUtilTest2 {
Connection con = null;
Statement st = null;
@org.junit.Test
public void update() {
//定义所要运行的查询语句
String sql = "insert into tb1(username,age,salary) values('zhangsan',30,4567.9)";
JDBCUtil jdbcUtil = new JDBCUtil();
try {
con = JDBCUtil.getConnection();
st = con.createStatement();
//调用
jdbcUtil.update(sql);
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtil.jdbcClose(con,st);
}
}
}