数据库工具类自定义DBUtils封装
- 第一步创建配置文件db.properties(注意在src文件夹下)
代码:
url=jdbc:mysql://127.0.0.1:3306/xd_web?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=root
password=root
driver=com.mysql.cj.jdbc.Driver
- 创建自定义工具类 CustomDBUtil
步骤——1.获取配置文件内容2.加载驱动3.建立连接方法4关闭连接方法
代码:
public class CustomDBUtil {
private static String driver;
private static String username;
private static String url;
private static String password;
static {
Properties properties=new Properties();
try {
//获取配置文件内容通过当前文件的类加载器通过配置文件名以流的形式加载
properties.load(CustomDBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
driver =properties.getProperty("driver");
url=properties.getProperty("url");
username=properties.getProperty("username");
password=properties.getProperty("password");
//加载驱动
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取链接
* @return
* @throws Exception
*/
public static Connection getconnection()throws Exception{
Connection connection=DriverManager.getConnection(url,username,password);
return connection;
}
/**
* 关闭资源库
* @param resultSet
* @param preparedStatement
* @param connection
*/
public static void close(ResultSet resultSet, PreparedStatement preparedStatement,Connection connection){
try {
if (resultSet!=null){
resultSet.close();
}
if (preparedStatement!=null){
preparedStatement.close();
}
if (connection!=null){
connection.close();
}
}catch (SQLException e){
throw new RuntimeException();
}
}
}
- Servlet调用使用
TestJDBCServlet
代码:
@WebServlet("/testJDBCServlet")
public class TestJDBCServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String idStr=req.getParameter("id");
int id=Integer.parseInt(idStr);
try {
//调用连接方法
Connection connection= CustomDBUtil.getconnection();
//执行语句
PreparedStatement preparedStatement=connection.prepareStatement("select * from user where id=?");
preparedStatement.setInt(1,id);
ResultSet resultSet= preparedStatement.executeQuery();
//获取结果
while (resultSet.next()){
System.out.println("用户名 name="+resultSet.getString("username")+"练习方式 WeChat="+resultSet.getString("wechat"));
}
//调用关闭连接方法
CustomDBUtil.close(resultSet,preparedStatement,connection);
}catch (Exception e){
e.printStackTrace();
}
}
}
结果截图: