本文主要是介绍setAutoCommit方法解释及数据库连接封装类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
java sql包下的Connection类里的setAutoCommit方法
在程序中可能一个业务包含两个或两个以上的sql操作,这是就需要把两个sql封装成一个事务提交,
setAutoCommit默认是ture的状态,表示每个sql自动提交。
所以我们根据项目情况一般吧它设为false,然后再后边手动纸箱commit或rollback。
DB数据库封装类:
package com.project.util;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;import org.apache.log4j.Logger;public class DB{private static Logger logger=Logger.getLogger(DB.class.getName());protected String _driver;protected String _url;protected String _user;protected String _passwd;protected String _host;protected String _port;protected Connection _conn;protected boolean _Connected = false;protected boolean _autoCommit=true;//default:truepublic DB(String driver, String url, String user, String passwd){_driver = driver;_url=url;_user = user;_passwd = passwd;}public void connect() throws Exception {try {logger.debug("begin connect db");Class.forName(_driver);_conn = DriverManager.getConnection(_url, _user, _passwd); _Connected = true;logger.debug("db connected");_conn.setAutoCommit(_autoCommit);} catch (Exception e) {logger.error("db error" + e.getMessage());}}public Connection get_conn() throws Exception{if (!_Connected)try {connect();} catch (Exception e) {throw e;}return _conn;}public void commit(){try{if(!_conn.getAutoCommit())_conn.commit();}catch(Exception e){logger.error(e);}}public void close() throws Exception {try {_conn.close();_Connected = false;logger.debug("db closed"); } catch (SQLException e) {logger.error(e.getMessage());throw new Exception(e);}}public void set_autoCommit(boolean autoCommit){this._autoCommit=autoCommit;}public void set_connectClosed(){_Connected=false;}public String get_url() {return _url;}}
这篇关于setAutoCommit方法解释及数据库连接封装类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!