package utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 这是连接数据库的工具类、 获取getcon 获取ds 获取res
*
* @author Aypak
*
*/
public class DBUtils {
// 声明driver
private static String driver = "com.mysql.jdbc.Driver";
// 声明连接地址uri
private static String url = "jdbc:mysql://192.168.137.244:3306/family?useUnicode=true&characterEncoding=utf8";
// 声明用户名
private static String name = "root";
// 声明密码
private static String pwd = "1234";
public DBUtils() {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Classforname错误");
}
}
// 获取连接con
public Connection getCon() {
Connection con = null;
try {
con = DriverManager.getConnection(url, name, pwd);
} catch (SQLException e) {
throw new RuntimeException("获取con错误");
}
return con;
}
// colse方法.需要关闭的有con,PreparedStatement ps,ResultSet rs
//为什么不分成三个方法写呢,因为这样最后只调用一个代码就ok所以。。。。
public void closeCon(Connection con, PreparedStatement ps, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
}
}
}
}
}
}
}
日常之记,如有错误请指出3Q!