JDBC封装数据库连接与关闭的工具类(含事务提示)

0.src目录下创建配置文件:db.properties,内容如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=1234

1.封装工具类,内容如下:

package cn.xiyou.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 使用JDBC进行数据库连接与关闭的工具类
 * 
 * @author XIAOHU
 * @since 2018-04-08
 */
public class JDBCUtil {

	private static String driver;
	private static String url;
	private static String username;
	private static String password;

	static {
		init();
	}

	/**
	 * 初始化数据库连接数据(从properties文件中读取)
	 */
	public static void init() {
		Properties prop = new Properties();
		InputStream is = 
					JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
		try {
			prop.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		driver = prop.getProperty("jdbc.driver");
		url = prop.getProperty("jdbc.url");
		username = prop.getProperty("jdbc.username");
		password = prop.getProperty("jdbc.password");
	}

	/**
	 * 获取数据库连接
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 释放所有资源
	 * 
	 * @param rs
	 *            结果集
	 * @param st
	 *            Statement对象
	 * @param conn
	 *            数据库连接
	 */
	public static void closeAll(ResultSet rs, Statement st, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}

2.事务提示:

//获取连接
Connection conn = JDBCUtil.getConnection();
conn.setAutoCommit(false);//关闭数据库事务自动提交

//测试SQl1
String sql = "update dept set DEPTNO=? where LOC=?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setInt(1, 1);
pst.setString(2, "NEW YORK");
int rows = pst.executeUpdate();

//测试SQl2
String sql2 = "update emp set name=? where id=?";
PreparedStatement pst2 = conn.prepareStatement(sql2);
pst2.setString(1, "我");
pst2.setInt(2, 2);
int rows2 = pst2.executeUpdate();

//手动事务提交
conn.commit();

你可能感兴趣的:(Java代码)