java连接数据库(JDBC)

public class DBConnection {
	private static final Log logger = LogFactory.getLog(DBConnection.class);

	/**
	 * 在本地测试时用本方法连接数据库
	 * 
	 * @return Connection
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			Context initCtx = new InitialContext();
			Context ctx = (Context) initCtx.lookup("java:comp/env");
			DataSource ds = (DataSource) ctx.lookup("jdbc/channel");
			conn = ds.getConnection();
		} catch (Throwable se) {
			logger.error("getConnection ERROR!" + se);
		}
		return conn;
	}

	/**
	 * 关闭数据库连接
	 * 
	 * @param conn
	 *            Connection
	 */
	public static void closeConnection(Connection conn) {
		try {
			if (conn != null && !conn.isClosed()) {
				conn.close();
			}
		} catch (Exception e) {
		}
		conn = null;
	}

	public static void closeStatement(Statement s) {
		try {
			if (s != null) {
				s.close();
			}
		} catch (Exception e) {
		}
		s = null;
	}

	public static void closeResultSet(ResultSet r) {
		try {
			if (r != null) {
				r.close();
			}
		} catch (Exception e) {
		}
		r = null;
	}

	/**
	 * 从数据库中取下一个序列键
	 * 
	 * @param conn
	 *            Connection
	 * @param sequence
	 *            String 序列名称
	 * @throws SQLException
	 * @return long
	 */
	public static int getNextSequence(Connection conn, String sequence)
			throws SQLException {
		int sequenceno = 0;
		PreparedStatement s = null;
		ResultSet r = null;
		try {
			String sql = "select " + sequence.trim() + ".nextval from DUAL";
			s = conn.prepareStatement(sql);
			r = s.executeQuery();
			if (r.next()) {
				sequenceno = r.getInt(1);
			}
		} catch (SQLException e) {
			throw e;
		} finally {
			closeResultSet(r);
			closeStatement(s);
		}
		return sequenceno;
	}

你可能感兴趣的:(java,sql,jdbc)