JdbcUtil:JDBC工具类

JdbcUtil:JDBC工具类
import java.io.IOException;
import java.io.InputStream;
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 JdbcUtil {

private static String driverClass;
private static String url;
private static String user;
private static String password;

static{
try {
ClassLoader cl = JdbcUtil.class.getClassLoader();
InputStream in = cl.getResourceAsStream("dbcfg.properties");
Properties props = new Properties();
props.load(in);
driverClass = props.getProperty("driverClass");
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");

Class.forName(driverClass);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}


public static Connection getConnection() throws Exception{
Connection conn = DriverManager.getConnection(url,user, password);
return conn;
}
public static void release(ResultSet rs,Statement stmt,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}

}



//配置文件dbcfg.properties

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/day15
user=root
password=sorry



//使用

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;


import org.junit.Test;


import com.itheima.util.JdbcUtil;


public class JdbcDemo6 {
@Test
public void testAdd(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
stmt = conn.createStatement();
stmt.executeUpdate("insert into users (name,password,email,birthday) values ('范青霞','123','fqx@itcast.cn','2000-10-01')");
}catch(Exception e){
throw new RuntimeException(e);
}finally{
JdbcUtil.release(rs, stmt, conn);
}
}
@Test
public void testUpdate(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
stmt = conn.createStatement();
stmt.executeUpdate("update users set password=111 where id=4");
}catch(Exception e){
throw new RuntimeException(e);
}finally{
JdbcUtil.release(rs, stmt, conn);
}
}
@Test
public void testDelete(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
stmt = conn.createStatement();
stmt.executeUpdate("delete from users where id=1");
}catch(Exception e){
throw new RuntimeException(e);
}finally{
JdbcUtil.release(rs, stmt, conn);
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值