public int create( ) {
Connection con = null;
Statement sm = null;
ResultSet rs = null;
PreparedStatement ps = null;
StringBuffer sb = new StringBuffer();
sb.append("INSERT INTO tx_test (");
sb.append("TITLE,PRODUCT_ID,COMMENTATOR,CONTENT");
sb.append(" ) ");
sb.append(" VALUES (");
sb.append("?,?,?,?");
sb.append(")");
int id=0;
try {
con = ds.getConnection();
ps = con.prepareStatement(sb.toString());
ps.setString(1, "");
ps.setInt(2, 1);
ps.setString(3, "");
ps.setString(4, "");
ps.execute();
sm = con.createStatement();
sm.execute("SELECT LAST_INSERT_ID() LAST_INSERT_ID");
rs = sm.getResultSet();
if (rs != null) {
if (rs.next()) {
int iRet = rs.getInt("LAST_INSERT_ID");
id = iRet;
}
}
rs.close();
sm.close();
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (ps != null) {
ps.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
try {
if (con != null) {
con.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return id;
}
- Jun 07 Sun 2015 18:24
[JAVA] Mysql 插入記錄,返回最後插入記錄的自動編號ID
文章標籤
全站熱搜
留言列表