iT邦幫忙

2025 iThome 鐵人賽

DAY 2
0

目的

建立User保存使用者資料
建立UserDAO操作資料庫,存/查資料

1.在model資料夾下新增class User(封裝users表裡的記錄)
https://ithelp.ithome.com.tw/upload/images/20251008/20178845RshnikGXp7.jpg
2.開始寫User程式
private int userId:先宣告users表裡的欄位。
public User:初始化物件在建立物件時會自動被呼叫(一定要跟類別名一樣,且不會回傳)。
public int getUserId、public、public void setUserId:供外部程式讀取或修改。
public String toString:覆寫一個method toString方便印出物件內容。
https://ithelp.ithome.com.tw/upload/images/20251008/20178845lK93JzBp40.jpg
https://ithelp.ithome.com.tw/upload/images/20251008/201788452sQcBwTNzp.jpg
3.在dao資料夾下新增class UserDAO(存users表的資料)
https://ithelp.ithome.com.tw/upload/images/20251009/20178845IGVv3ZPwev.jpg
4.開始寫UserDAO程式
public class UserDAO:宣告一個變數conn,為資料庫連線物件。
public UserDAO:把傳進來的connection存到UserDAO的conn變數裡。
https://ithelp.ithome.com.tw/upload/images/20251009/20178845fG91wfa70c.jpg


addUser(新增使用者):傳入User物件,丟出例外不在這執行。
INSERT INTO:先準備在users表插入值,用?代替。
pstmt=conn.prepareStatement(sql):會回傳一個準備好的語句物件。
pstmt.setInt(1,name):將第一個?設為name且為字串。
https://ithelp.ithome.com.tw/upload/images/20251009/20178845J9pzqgxjAQ.jpg


getUserId(查詢使用者):傳入userId,丟出例外不在這執行。
SELECT FROM:查詢users表裡的userId=? 。
ResultSet rs:pstmt.executeQuery():將查到的結果存入rs。
if(rs.next):如果找到符合的使用者,就從資料庫讀出所有欄位,然後建立一個User物件,把資料放進去並回傳,沒有就回傳null。
https://ithelp.ithome.com.tw/upload/images/20251009/20178845CFWy8wlK6t.jpg


deleteUser(刪除使用者):指定刪除userId,並在這拋出例外。
DeLETE FROM:刪除語句。
https://ithelp.ithome.com.tw/upload/images/20251009/20178845cIxkE4NUBV.jpg


updateUser(更新使用者資料):丟入user使用者物件,拋出例外不在這執行。
UPDATE users SET:更新users表中符合userId的那筆資料。
https://ithelp.ithome.com.tw/upload/images/20251009/20178845KHsk0nyfFO.jpg


上一篇
新增food資料庫
系列文
飲食營養追蹤 + 健康分析 Web 系統5
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言