JDBC-DBUtil工具类
一、创建DBUtil工具类
import java.sql.*;
public class DBUtil {
/**
* 工具类的构造方法都是私有的
* 因为工具类的方法都是静态的,不需要new对象,直接使用类型名.的方式调用
*/
private DBUtil() {
}
/**
* 静态代码块在类加载时执行,并且只执行一次
*/
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接对象
*
* @return 返回数据库连接对象
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/firstbase", "root", "123456");
}
/**
* 关闭资源
* @param con 连接对象
* @param ps 数据库操作对象
* @param rs 结果集
*/
public static void close(Connection con, PreparedStatement ps, ResultSet rs){
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (ps != null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con != null){
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
二、测试DBUtil工具类
/**
* 1.测试工具类DBUtil是否好用;
* 2.以及模糊查询怎么写
*/
import java.sql.*;
public class JdbcTest10 {
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DBUtil.getConnection();
String sql = "select * from t_users where userName like ?";
ps = con.prepareStatement(sql);
ps.setString(1,"_i%");
rs = ps.executeQuery();
while(rs.next()){
String id = rs.getString(1);
String username = rs.getString(2);
String password = rs.getString(3);
System.out.println(id+ " " +username +" " +password);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
DBUtil.close(con, ps, rs);
}
}
}
When nothing seems to help, I go look at a stonecutter hammering away at his rock, perhaps a hundred times without as much as a crack showing in it. Yet at the hundred and first blow it will split in two, and I know it was not that blow that did it, but all that had gone before. -- Jacob Riis