[Playframework+JPA+mysql] 資料更新與刪除
阿新 • • 發佈:2019-01-28
說明: 刪除與更新用的方法類似,這裡僅以更新資料為例。
方法一,Play!封裝的JPA:
查詢後,直接更新欄位並儲存
long id = 1;
DogEntity entity = DogEntity.findById(id);
entity.name = "Mike";
entity.color = "brown";
entity.save();
方法二, 原生JPA—JPA.em().createQuery(sql).executeUpdate():
String sql = "update DogEntity set " +
"name ='Mike' , color = 'brown' " +
"where id = 1";
int count = JPA.em().createQuery(sql).executeUpdate();
logger.info("刪除個數:" + count);
方法三, JDBC—pstmt.executeUpdate():
String sql = "update DogEntity set " +
"name = ?, color = ?, +
"where id = ?";
logger.debug(sql);
Connection conn = null;
PreparedStatement pstmt=null;
boolean flag = false;
try {
conn = DBTool.getConnection();
} catch (Exception e) {
e.printStackTrace();
DBTool.close(null, pstmt, conn);
logger.info(" 資料庫連接出錯");
}
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,"Mike");
pstmt.setString(2, "brown");
pstmt.setLong(3, 1);
int count = pstmt.executeUpdate();
logger.debug("更新條數:" + count);
flag = true;
} catch (SQLException e) {
e.printStackTrace();
logger.info(" SQL語句出錯");
}finally{
DBTool.close(null, pstmt, conn);
}
return flag;