jdbcutils.java

来自「struts做得固定资产管理系统 带毕业论文完整版」· Java 代码 · 共 140 行

JAVA
140
字号
/*
 * @(#)JdbcUtils.java Aug 3, 2007
 * Copyright 2007 ThinkJ organization, Inc. All rights reserved
 */
package com.qrsx.appcam.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JdbcUtils {

	private static ThreadLocal threadConnection = new ThreadLocal();

	/**
	 * ��ȡmysql��l��
	 * 
	 * @return
	 */
	public static Connection getMySqlConnection() {
		Connection conn = null;
		String url = null;

		try {
			Class.forName("com.mysql.jdbc.Driver");
			url = "jdbc:mysql://localhost:3306/myAppcam";
			conn = DriverManager.getConnection(url, "root", "");

			if (conn == null) {
				throw new SQLException("Can't connect MySql!");
			}

		} catch (ClassNotFoundException e2) {
			e2.printStackTrace();
		} catch (SQLException e) {
			System.out.println("url:" + url);
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * ��ȡ��ǰ��Connection
	 * 
	 * @return
	 */
	public static Connection getCurrentConnection() {
		Connection conn = (Connection) threadConnection.get();
		if (conn == null) {
			conn = getMySqlConnection();
			threadConnection.set(conn);
		}
		return conn;
	}

	/**
	 * ��ȡ��ǰ��Connection
	 * 
	 * @return
	 */
	public static Connection getCurrentConnection(boolean isTransaction) {
		Connection conn = getCurrentConnection();

		try {
			if (isTransaction) {
				conn.setAutoCommit(false);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return conn;
	}

	/**
	 * �رյ�ǰ��Connection
	 * 
	 */
	public static void closeCurrentConnection() {
		try {
			Connection conn = (Connection) threadConnection.get();
			threadConnection.set(null);
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * �رյ�ǰ��Connection
	 * 
	 */
	public static void closeConnection(Connection conn) {
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * ������
	 */
	public static void beginTransaction() {
		try {
			Connection conn = (Connection) threadConnection.get();
			conn.setAutoCommit(false);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * �ύ����
	 */
	public static void commitTransaction() {
		try {
			Connection conn = (Connection) threadConnection.get();
			conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * �ύ����
	 */
	public static void rollbackTransaction() {
		try {
			Connection conn = (Connection) threadConnection.get();
			conn.rollback();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}

⌨️ 快捷键说明

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