编程语言
首页 > 编程语言> > java – 语句关闭后不允许任何操作

java – 语句关闭后不允许任何操作

作者:互联网

在语句关闭后,我收到了Exception,并允许签名.在我的Java代码中,我试图将值插入数据库.错误签名说我的Statement对象被关闭了,我试图在我的代码中再次使用它,但我正在努力理解的是为什么会发生这种情况,因为我没有关闭代码中的任何连接.

这是Java代码.

public class DataBaseAccessUtils {

    private static String jdbcUrl = 
            AppConfig.findMap("BXRequestTracker").get("jdbcUrl").toString();
    private static Connection connection = null;
    private static Statement statement = null;

    public static void insertHostname(String hostname, String rid, String fleet, String locale)
    {
        locale.toUpperCase();
        String sql = "UPDATE " + locale + "REQUESTTRACKER SET " + fleet 
                + "='" + hostname + "' WHERE RID='" + rid + "'";
        try {
            statement.execute(sql);
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static Statement connectToDatabase() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(DataBaseAccessUtils.jdbcUrl);
            statement = connection.createStatement();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return statement;
    }

此外,我发现当存在单个线程执行时,错误不会出现,当多个线程试图同时更新数据库时,它会出现.

解决方法:

创建一个用于连接管理的Utility类,以便在整个应用程序中的单点管理它.

每次需要新连接时都不要加载DataSource.

示例代码:

public class ConnectionUtil {

    private DataSource dataSource;

    private static ConnectionUtil instance = new ConnectionUtil();

    private ConnectionUtil() {
        try {
            Context initContext = new InitialContext();
            dataSource = (DataSource) initContext.lookup("JNDI_LOOKUP_NAME");
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    public static ConnectionUtil getInstance() {
        return instance;
    }

    public Connection getConnection() throws SQLException {
        Connection connection = dataSource.getConnection();
        return connection;
    }

    public void close(Connection connection) throws SQLException {
        if (connection != null && !connection.isClosed()) {
            connection.close();
        }
        connection = null;
    }

}

始终关闭连接并在try-catch-finally中处理它

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = ConnectionUtil.getInstance().getConnection();

            ...
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                ConnectionUtil.getInstance().close(conn);
            }
        }

标签:mysql-error-1064,java,mysql
来源: https://codeday.me/bug/20191006/1858872.html