[color=blue]这个是我的通用DAO类,更新和查询都是用的公共的pstmt.execute.需要返回新插入数据的主键时,sql语句的格式应该是"insert into userinfo(name,pwd)values(?,?)select @@identity";然后通过pstmt.getGeneratedKeys()便可获取新插入数据的主键。业务DAO类使用res.get(1)获取主键。这个问题今天困扰了我老长时间。[/color]
[quote]import org.syh.oa.system.db.DBConnection;
public class BaseDao {
private static Connection con;
private static PreparedStatement pstmt;
//通用业务操作
public static void execute(String sql, List parms) {
try {
con = DBConnection.getDBCon();
pstmt = con.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
if (parms != null) {
setParam(pstmt, parms);
}
pstmt.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
//返回插入的主键
public static ResultSet getKeys() throws SQLException{
return pstmt.getGeneratedKeys();
}
//返回结果集
public static ResultSet getRes() {
ResultSet result = null;
try {
result = pstmt.getResultSet();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
//返回影响行数
public static int getUpdateCount() {
int no = 0;
try {
no = pstmt.getUpdateCount();
} catch (Exception e) {
e.printStackTrace();
}
return no;
}
//循环给参数赋值
public static void setParam(PreparedStatement pstmt, List parms) {
try {
for (int i = 0; i < parms.size(); i++) {
Object obj = (Object) parms.get(i);
pstmt.setObject(i + 1, obj);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//关闭资源
public static void closeAll() {
try {
if (con != null) {
con.close();
}
if (pstmt != null) {
pstmt.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}[/quote]
[quote]import org.syh.oa.system.db.DBConnection;
public class BaseDao {
private static Connection con;
private static PreparedStatement pstmt;
//通用业务操作
public static void execute(String sql, List parms) {
try {
con = DBConnection.getDBCon();
pstmt = con.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
if (parms != null) {
setParam(pstmt, parms);
}
pstmt.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
//返回插入的主键
public static ResultSet getKeys() throws SQLException{
return pstmt.getGeneratedKeys();
}
//返回结果集
public static ResultSet getRes() {
ResultSet result = null;
try {
result = pstmt.getResultSet();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
//返回影响行数
public static int getUpdateCount() {
int no = 0;
try {
no = pstmt.getUpdateCount();
} catch (Exception e) {
e.printStackTrace();
}
return no;
}
//循环给参数赋值
public static void setParam(PreparedStatement pstmt, List parms) {
try {
for (int i = 0; i < parms.size(); i++) {
Object obj = (Object) parms.get(i);
pstmt.setObject(i + 1, obj);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//关闭资源
public static void closeAll() {
try {
if (con != null) {
con.close();
}
if (pstmt != null) {
pstmt.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}[/quote]