dbconnection.java

来自「又一个课程设计 简易 JSP 论坛 功能较简单的那种, 界面上模仿了 Disc」· Java 代码 · 共 87 行

JAVA
87
字号
package cn.ialvin.sql;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConnection {
	private static ConnectionPool pool = null;
	private Connection coxn = null;
	public DBConnection(ConnectionPool pool) throws SQLException {
		if (DBConnection.pool == null)
			DBConnection.pool = pool;
	}

	public synchronized Connection getConnection() throws PoolBusyException {
		Connection coxn = null;
		if (DBConnection.pool != null)
			coxn = DBConnection.pool.getConnection();
		return coxn;
	}

	public PreparedStatement prepareStatement(String sql) throws SQLException {
		if (this.coxn == null) this.coxn = this.getConnection();
		PreparedStatement stmt = this.coxn.prepareStatement(sql);
		return stmt;
	}
	
	public void closeStatement(Statement stmt) {
		if (stmt == null) return;
		try { stmt.close(); } catch (SQLException e) {}
	}
	
	public void closeResultSet(ResultSet rs) {
		if (rs == null) return;
		try { rs.close(); } catch (SQLException e) {}
	}

	public synchronized void close() {
		if (this.coxn == null) return;
		if (DBConnection.pool != null) {
			DBConnection.pool.putConnection(this.coxn);
		} else {
			try {
				if (!this.coxn.isClosed())
					this.coxn.close();
			} catch(SQLException e) {}
		}
		this.coxn = null;
	}

	public synchronized void finalize() throws Throwable {
		this.close();
		super.finalize();
	}
	
	public String readText(Reader reader) {
		if (reader == null) return "";
		StringBuffer sb = new StringBuffer();
		BufferedReader br = new BufferedReader(reader);
		String line = null;
		try {
			if ((line = br.readLine()) != null);
				sb.append(line);
			while ((line = br.readLine()) != null) {
				sb.append("\r\n");
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	public String getLongText(int key, ResultSet rs) throws SQLException {
		Reader reader = rs.getCharacterStream(key);
		return this.readText(reader);
	}
	public String getLongText(String key, ResultSet rs) throws SQLException {
		Reader reader = rs.getCharacterStream(key);
		return this.readText(reader);
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?