MySQL事务和properties数据库连接

来源:互联网 发布:51铃声馆软件下载 编辑:程序博客网 时间:2024/05/29 19:26
package com.jdbc;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;import java.sql.Savepoint;import java.sql.Statement;public class Account {     /* 1.开启事务conn.setAutoCommit(false);2.设置事务回滚点sp=conn.setSavePoint();3.发生异常则事务回滚conn.rollback(sp);4.提交事务conn.commit();*/public static void main(String args[]) throws ClassNotFoundException, SQLException{Connection conn=DBUtil.getConnection();try{conn.setAutoCommit(false);//设置非自动提交Savepoint sp=conn.setSavepoint();//异常出现就回滚的回滚点Statement stat=conn.createStatement();PreparedStatement ps1=conn.prepareStatement("update employees set money=money+? where name=?");ps1.setInt(1,100);ps1.setString(2,"李四");int i=ps1.executeUpdate();int k=10/0;//模拟出的异常}catch(Exception e){e.printStackTrace();conn.rollback();//捕捉到异常发生回滚}PreparedStatement ps2=conn.prepareStatement("update employees set money=money-? where name=?");ps2.setInt(1,100);ps2.setString(2, "张三");int j=ps2.executeUpdate();    conn.commit();//手动提交   }}


package com.jdbc;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;public class PropertiesUtil {  private static Properties pro=new Properties();    static{InputStream inStream=PropertiesUtil.class.getResourceAsStream("/com/jdbc/jdbc.properties");try {pro.load(inStream);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static String getPropertyValue(String key){return pro.getProperty(key);}}

package com.jdbc;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class DBUtil {   private static String drivername;   private static String url;   private static String accouont;   private static String password;      static{drivername=PropertiesUtil.getPropertyValue("jdbc.drivername");url=PropertiesUtil.getPropertyValue("jdbc.url");accouont=PropertiesUtil.getPropertyValue("jdbc.username");password=PropertiesUtil.getPropertyValue("jdbc.password");}   public static Connection getConnection() throws ClassNotFoundException, SQLException{Connection conn;Class.forName(drivername);conn=DriverManager.getConnection(url,accouont,password);return conn;}      }


#jdbc.drivername=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/bumen?characterEncoding=utf8jdbc.username=rootjdbc.password=123456

注意:回滚要在事务提交之前

0 0
原创粉丝点击