您的位置:首页 > 其它

JDBC工具类抽取方式二(测试添加操作)

2018-03-28 05:20 417 查看
创建配置文件:

package cn.itheima.jdbc;
/**
* 提供获取连接和释放资源的方法
* @author XING
*
*/

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class JDBCUtils_V2 {
private static String driver;
private static String url;
private static String username;
private static String password;

/**
* 静态代码块加载配置文件信息
*/
static{
ResourceBundle bundle = ResourceBundle.getBundle("db");
driver = bundle.getString("driver");
url = bundle.getString("url");
username = bundle.getString("username");
password = bundle.getString("password");
}

/**
* 获取连接方法
*
* @return
*/
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}

public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs){
if (rs !=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt !=null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn !=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

package cn.itheima.jdbc.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.junit.Test;

import cn.itheima.jdbc.JDBCUtils_V1;
import cn.itheima.jdbc.JDBCUtils_V2;

/**
* 测试工具类
*
* @author XING
*
*/
public class TestUtils {
/**
* 添加用户信息方法
*/
@Test
public void testAdd(){
Connection conn = null;
PreparedStatement pstmt = null;
try {
//1.获取连接
conn = JDBCUtils_V2.getConnection();
//2.编写SQL语句
String sql = "insert into tbl_user values(null,?,?)";
//3.获取执行SQL语句对象
pstmt = conn.prepareStatement(sql);
//4.设置参数
pstmt.setString(1, "lisi");
pstmt.setString(2, "hehe");
//5.执行插入操作
int row = pstmt.executeUpdate();
if(row>0){
System.out.println("添加成功");
}else{
System.out.println("添加失败");
}

} catch (Exception e) {
throw new RuntimeException(e);
}finally{
//6.释放资源
JDBCUtils_V2.release(conn, pstmt, null);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: