[Java Web学习]JDBC事务处理

1. Spring中加入数据库的bean

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost:3306/MY_FIRST_STUDY"
p:username="root"
p:password="123456"/>

2. 利用Connection

 @Autowired
private DataSource dataSource; public int registerUserInfo(String userName, String passwordMD5, String createTime, String userType, String description) {
Connection connection = DataSourceUtils.getConnection(dataSource);
try {
connection.setAutoCommit(false);
StringBuilder userSalt = new StringBuilder("lizhix");
userSalt.append(System.currentTimeMillis());
StringBuilder insertUserInfo = new StringBuilder("INSERT INTO USER_INFO (USER_NAME, PASSWORD, CREATE_TIME, USER_TYPE, DESCRIPTION) " +
"VALUES (\"" + userName + "\",\"" + (passwordMD5 + userSalt) + "\",\"" + createTime + "\",\"" + userType + "\",\"" + description + "\");"); StringBuilder insertUserSalt = new StringBuilder("INSERT INTO USER_SALT (USER_NAME, USER_SALT) VALUES (\"" + userName + "\",\"" + userSalt + "\");"); int flag1 = jdbcTemplate.update(insertUserInfo.toString());
int flag2 = jdbcTemplate.update(insertUserSalt.toString()); connection.commit();
return flag1 & flag2;
} catch (SQLException se) {
try {
connection.rollback();
connection.close();
return 0;
} catch (Exception e) {
e.printStackTrace();
}
}
return -1;
}
上一篇:asp.net 后台获取flv视频地址进行播放


下一篇:python网络编程--线程Semaphore(信号量)