多线程访问数据库(当多用户同时访问时会出现数据错误)
action类:
public class CheckAction
{
private CheckDAO checkDAO = new CheckDAO();
public CheckDAO getCheckDAO()
{
return checkDAO;
}
public void setCheckDAO(CheckDAO checkDAO)
{
this.checkDAO = checkDAO;
}
public String update()
{
checkDAO.update();
return "update ";
}
}
DAO类:
public class CheckDAO
{
private Connection conn = null;
private String sql = " ";
private ResultSet rSet = null;
//将数据插入到TABLE1,然后获自增的ID,再更新TABLE2,当只有一个用户操作时数据正确,多用户并发数据就不正确了
public void update()
{
try
{
conn = JdbcUtils.getConnection();
sql= "INSERT INTO TABLE1 (NAME,PASSWORD) VALUES ( 'NAME1 ', 'NAME1 ') ";
conn.prepareStatement(sql).executeUpdate();
sql = "SELECT IDENT_CURRENT( 'TABLE1 ') NewId ";
rSet = conn.prepareStatement(sql).executeQuery();
rSet.next();
sql= "UPDATE TABLE2 SET table1_id=rSet.getString( "NewId "), IsDone= 'Y ' ";
conn.prepareStatement(sql).executeUpdate();
}
finally
{
JdbcUtils.free(rSet,null,conn);
}
}
}
数据库连接:
public class JdbcUtils
{
private static DataSource myDataSource = null;
private JdbcUtils()
{
}
static
{
try
{
Properties prop = new Properties();
InputStream is = JdbcUtils.class.getClassLoader()
.getResourceAsStream( "dbcpconfig.properties ");
prop.load(is);
myDataSource = BasicDataSourceFactory.createDataSource(prop);
}
catch (Exception e)
{
throw new
ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws
SQLException {
// return DriverManager.getConnection(url, user, password);
return myDataSource.getConnection();
}
public static void free(ResultSet rs, Statement st, Connection conn)
{
t