我收到带有签名的异常No operations allowed after statement closed.
在我的 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;
}
我还观察到,当存在单线程执行时,错误不会出现,当多个线程尝试同时更新数据库时,错误就会出现。
创建一个用于连接管理的实用程序类,以便在整个应用程序中的单点上对其进行管理。
不要加载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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)