java.sql.SQLException connection closed Query报错

网站注册页面保存用户时出现错误

java.sql.SQLException: connection closed Query: insert into User ('Username','UserPassword','Head','Email','Phone','Birthday','Sex','RegisterData','Level','Exp') VALUES (?,?,?,?,?,?,?,?,?,?) Parameters: [admin, 123456, null, 1736612045@qq.com, 13175451455, 2022-1-1, ??·, 2022-02-08, 1, 0]
	at org.apache.commons.dbutils.AbstractQueryRunner.rethrow(AbstractQueryRunner.java:527)
	at org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:531)
	at org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:444)
	at com.fingercoding.dao.impl.BaseDao.Update(BaseDao.java:27)
	at com.fingercoding.dao.impl.UserDaoImpl.saveUser(UserDaoImpl.java:26)
	at com.fingercoding.servlet.impl.UserServletImpl.registerUser(UserServletImpl.java:14)
	at com.fingercoding.web.RegisterUserServlet.doPost(RegisterUserServlet.java:45)

sql语句字段名使用`(反引号),’(单引号)均报此错误,求助

你代码怎么写的啊,贴出来啊

  • DAO层
public int saveUser(User user) {
    String sql =“insert into User (‘Username’,‘UserPassword’,‘Head’,‘Email’,‘Phone’,‘Birthday’,‘Sex’,‘RegisterData’,‘Level’,‘Exp’) VALUES (?,?,?,?,?,?,?,?,?,?)”;
    return Update(sql,user.getUserName(),user.getUserPassword(),user.getHead(),user.getEmail(),user.getPhone(),user.getBirthday(),user.getSex(),user.getRegisterDate(),user.getLevel(),user.getExp());
}

public int Update(String sql, Object… args) {
    try {
        return queryRunner.update(connection,sql, args);
    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
        DButils.close(connection);
    }
    return -1;
}
  • Servlet层
public void registerUser(User user) {
    userDao.saveUser(user);
}

看着意思,不像是SQL异常。而是JDBC连接已经关闭了。

连接没问题,测试类都能成功运行

代码不会骗你。你可以在执行更新之前。判断一下连接是否关闭。JDBC的Connection 对象有一个方法。

boolean isClosed() throws SQLException;
1 Like

好的我试试

自己看源码,不用你关闭连接,他自己在finally里面做了,你把你的关闭连接的代码去掉,我这个是commons-dbutils-1.7

下面是源码

public int update(String sql, Object... params) throws SQLException {
      Connection conn = this.prepareConnection();
      return this.update(conn, true, sql, params);
 }

private int update(Connection conn, boolean closeConn, String sql, Object... params) throws SQLException {
      if (conn == null) {
          throw new SQLException("Null connection");
      } else if (sql == null) {
          if (closeConn) {
              this.close(conn);
          }

          throw new SQLException("Null SQL statement");
      } else {
          PreparedStatement stmt = null;
          int rows = 0;

          try {
              stmt = this.prepareStatement(conn, sql);
              this.fillStatement(stmt, params);
              rows = stmt.executeUpdate();
          } catch (SQLException var11) {
              this.rethrow(var11, sql, params);
          } finally {
              this.close(stmt);
              if (closeConn) {
                  this.close(conn);
              }

          }

          return rows;
      }
}
1 Like

感谢,更新前Connection确实已经关闭了

感谢,很有帮助