原生Web开发中遇到的数据库资源问题

2019-11-24  本文已影响0人  陶然然_niit

1.环境和工具

2.问题描述

请求后端接口,使用Postman测试的时候,发现经常是第一次能请求到,后面就显示数据没找到(做了统一的异常结果处理)


Postman测试
后端日志

3.解决方法

在Tomcat中配置数据库连接,在web项目的web.xml中读入这个配置资源,并对数据库连接的工具类适当修改,问题得以解决。

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
    <Resource name="jdbc/datasource" auth="Container" type="javax.sql.DataSource"
    username="root" password="root" driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/db_blog?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false"
    maxTotal="100" maxIdle="30" maxWaitMillis="10000"/>
</Context>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
        version="4.0">
   <resource-ref>
       <description>jdbc/datasource</description>
       <res-ref-name>jdbc/datasource</res-ref-name>
       <res-type>javax.sql.DataSource</res-type>
       <res-auth>Container</res-auth>
   </resource-ref>
</web-app>
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_blog?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username=root
jdbc.password=root

package com.scs.web.blog.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author mq_xu
 * @ClassName DbUtil
 * @Description 数据库连接工具类
 * @Date 2019/11/10
 * @Version 1.0
 **/
public class DbUtil {
    private static Logger logger = LoggerFactory.getLogger(DbUtil.class);

    private static Properties properties;

    private DbUtil() {
    }

    // 使用静态代码块保证在类加载的时候立即加载对应的配置文件
    static {
        properties = new Properties();
        try {
            InputStream ins = DbUtil.class.getClassLoader().getResourceAsStream("db-config.properties");
            assert ins != null;
            properties.load(ins);
            Class.forName(properties.getProperty("jdbc.driverClassName"));
        } catch (FileNotFoundException e) {
            logger.error("数据库配置文件未找到");
        } catch (IOException e) {
            logger.error("数据库配置文件读写错误");
        } catch (ClassNotFoundException e) {
            logger.error("数据库驱动 未找到");
        }
    }


    /**
     * 获得数据库连接Connection
     *
     * @return Connection 数据库连接
     */
    public static Connection getConnection() {

        Connection connection = null;
        try {
            connection = DriverManager.getConnection(
                    properties.getProperty("jdbc.url"),
                    properties.getProperty("jdbc.username"),
                    properties.getProperty("jdbc.password"));
        } catch (SQLException e) {
            logger.error("数据库连接失败");
        }
        return connection;
    }

    /**
     * 关闭connection
     *
     * @param connection 连接池对象
     */
    public static void close(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭Statement
     *
     * @param statement
     */
    public static void close(Statement statement) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭ResultSet
     *
     * @param resultSet
     */
    public static void close(ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭Connection 以及Statement
     *
     * @param connection
     * @param statement
     */
    public static void close(Connection connection, Statement statement) {
        close(connection);
        close(statement);
    }

    /**
     * 关闭Connection,Statement以及ResultSet
     *
     * @param connection
     * @param statement
     * @param resultSet
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        close(connection, statement);
        close(resultSet);
    }
}
  @Override
    public void insert(User user) throws SQLException {
        Connection connection = DbUtil.getConnection();
        String sql = "INSERT INTO t_user (mobile,password) VALUES (?,?) ";
        PreparedStatement pst = connection.prepareStatement(sql);
        pst.setString(1, user.getMobile());
        pst.setString(2, user.getPassword());
        pst.executeUpdate();
        DbUtil.close(connection, pst);
    }
上一篇下一篇

猜你喜欢

热点阅读