Java 打开和关闭数据库
我正在开发一个应用程序,它在我的服务器上记录我的MySql数据库。每次我想使用数据库时,获取现有的连接,如果没有,我想这是第一次。当我插入或选择时,效果很好,但在咨询之后,当咨询结束时,我永远无法恢复连接,也无法返回咨询 我的数据库类Java 打开和关闭数据库,java,mysql,database,jdbc,Java,Mysql,Database,Jdbc,我正在开发一个应用程序,它在我的服务器上记录我的MySql数据库。每次我想使用数据库时,获取现有的连接,如果没有,我想这是第一次。当我插入或选择时,效果很好,但在咨询之后,当咨询结束时,我永远无法恢复连接,也无法返回咨询 我的数据库类 public class Database { /** * Gets just one instance of the class * Connects on construct * @returns connection */ private Conne
public class Database {
/**
* Gets just one instance of the class
* Connects on construct
* @returns connection
*/
private Connection _conn = null;
private long timer;
//singleton code
private static Database DatabaseObject;
private Database() {}
public static Database connect() {
if (DatabaseObject == null)
DatabaseObject = new Database();
return DatabaseObject._connect();
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
//end singleton code
/**
* Connects with the defined parameters on Config
* Prevents re-connection if object was already connected
* @throws SQLException
*/
private Database _connect() {
try {
if (this._conn == null || !this._conn.isValid(0)) {
try {
Class.forName("com.mysql.jdbc.Driver");
Properties connProps = new Properties();
connProps.put("user", Config.Config.DB_USER);
connProps.put("password", Config.Config.DB_PASS);
this._conn = DriverManager.
getConnection("jdbc:" + Config.Config.DB_DBMS + "://" + Config.Config.DB_HOST + ":"
+ Config.Config.DB_PORT + "/" + Config.Config.DB_NAME, Config.Config.DB_USER, Config.Config.DB_PASS);
timer = System.currentTimeMillis();
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
} catch (Exception e) {
System.out.println("Could not connect to DB");
e.printStackTrace();
}
} else {
try {
long tmp = System.currentTimeMillis() - timer;
if (tmp > 1200000) { //3600000 one hour ; 1200000 twenty minutes
System.out.println("Forcing reconnection ("+tmp+" milliseconds passed since last connection)");
this.close();
this._connect();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Forcing reconnection");
this._conn = null;
this._connect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
/**
* Closes connections
* This has to be invoked when database connection is no longer needed
* @throws SQLException
*/
public void close() throws SQLException {
if (this._conn != null) {
this._conn.close();
this._conn = null;
}
}
/**
* Getter for connection
* @return
*/
public Connection get() {
return this._conn;
}
}
我使用以下函数进行查询:
private Statement sment = null;
private PreparedStatement psment = null;
private ResultSet rset = null;
public boolean existsByNameAndUserId(String md5, int userId, int eventId) {
Connection conn = Database.connect().get();
try {
psment = conn.prepareStatement("SELECT * FROM files "
+ "WHERE user_id = ? AND md5 = ? AND evento_id = ?");
psment.setInt(1, userId);
psment.setString(2, md5);
psment.setInt(3, eventId);
rset = psment.executeQuery();
if (rset.next()) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private void close() {
try { if (rset != null) rset.close(); } catch (Exception e) {System.out.println(e.getMessage());};
try { if (psment != null) psment.close(); } catch (Exception e) {System.out.println(e.getMessage());};
try { if (sment != null) sment.close(); } catch (Exception e) {System.out.println(e.getMessage());};
}
在下一步中,我调用上面的函数来确定一个记录是否具有这些特征,如果没有,我就进行插入
String SQL_INSERT = "INSERT INTO files (evento_id, user_id, path, thumb, preview, width, height, md5, numero_corredor, created, modified) "
+ "VALUES (?,?,?,?,?,?,?,?,?,NOW(),NOW())";
public void save(List<components.File.Schema> files) throws SQLException {
try (
Connection conn = Database.connect().get();
PreparedStatement statement = conn.prepareStatement(SQL_INSERT);
) {
int i = 0;
for (components.File.Schema file : files) {
if(!existsByNameAndUserId(file.getMd5(), file.getUserId(), file.getEventId())){
statement.setInt(1, file.getEventId());
statement.setInt(2, file.getUserId());
statement.setString(3, file.getPath());
statement.setString(4, file.getPreview());
statement.setString(5, file.getThumb());
statement.setInt(6, file.getWidth());
statement.setInt(7, file.getHeight());
statement.setString(8, file.getMd5());
statement.setString(9, null);
statement.addBatch();
i++;
if (i % 1000 == 0 || i == files.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
}
您的问题是因为您将Connection conn=Database.connect.get放入了try with resources语句,这是您应该执行的操作,但它会关闭您的连接,并且当您再次调用它时(因为方法_connect没有有效的测试),它不会创建新的连接。有效的测试是这样的。_conn==null | |!这是。_conn.isValid0,实际上在您最初的测试中,您称之为。_conn.isValid0在我们的上下文中将返回false,因为连接已关闭,因此它不会创建一个新的连接,这不是我们想要的
响应更新:问题的第二部分是,在调用existsByNameAndUserId关闭当前连接的save方法中,您应该只关闭语句并让save方法关闭连接。请检查-尝试提供代码并尽可能解释,但不理解?我将尝试编写和添加更多代码@RazibNo,在我看来,最好的问题是简洁易懂的问题。我的问题是,当数据库查询工作正常时,第二个失败。无返回值,不属于异常,不获取错误。只是由于数据库连接丢失,我试图找出问题所在,但找不到原因。每次我使用数据库获取现有连接时,如果建立了连接,我会想到一个新的连接,但这对我不起作用。@Razib编辑我的帖子,希望能更好地理解它。Colas,您好,谢谢您的回答。我理解你说的,我想我想我添加了一个方法代码close,因为在这个方法中我不关闭数据库,我的post code中的editare和Failes不需要添加close方法,因为连接是自动关闭的,因此它已在try with resources语句的上下文中调用。我理解并修改我的代码以验证连接,正如您所说的,但仍然以相同的方式工作。在第一次咨询数据库时,我无法再次访问。我尝试了,但它是一样的,编辑我的帖子,让你看到我的代码,看看我对你所说的是否有逻辑错误,是否应该工作,如果我是你,我会使用数据源,但这不是这里的主题,你只是尝试调试,看看会发生什么?