技術產品無論是網站還是app,對於有一定的受衆的產品來說數據庫的應用是不可或缺的。沒有數據庫就好比一羣人在圖書館裏看書,大家都光着腳,管理員光靠味覺去捕捉腳臭的罪魁禍首估計有如海底撈針。但有了數據庫就不一樣了,給了每人一雙鞋,這時候想知道誰的腳臭就可以對鞋下工夫了。額… 這例子好惡心。總之,只爲說明一點,數據庫的作用及其架構無比重要。
根據的前幾篇博客所例,這個產品主要實現對用戶的管理,用戶登錄,用戶註冊以及用戶的個人信息的完善。先看數據看的工程架構:
其中的UserInfo包裏的表我只是添加了兩張:一張Pet表,一張User表。需要注意的是表中的外鍵,因爲外鍵的值的特殊性,它是由相關聯的表的id決定的,所以在聲明這個外鍵時必須用相關表(類)的對象聲明引用。
有了架構,接下來是功能的實現。
用戶登錄:
用戶登錄的首要條件是用戶名、密碼不爲空,其次是數據庫中存在該用戶名,並且密碼正確。
/**
* 查詢用戶是否存在,從而判斷是否允許登錄
* @param condition 查詢條件 password 對應的密碼
*/
public boolean queryMember(String condition,String condition_password){
String username = null;
String password = null;
try{
Connection con = this.getConnection();
//定義SQL語句
String sql2 = "select * from user where username = ?";
//獲取預編譯SQL執行對象,同時檢測數據庫中是否已經存在該SQL語句,如果存在,不存入SQL語句,如果不存在則存入SQL語句
PreparedStatement pstmt = con.prepareStatement(sql2);
//給每一個?佔位符指定數據
pstmt.setString(1, condition);
ResultSet rs = pstmt.executeQuery();//執行
System.out.println("id username password mail");
while(rs.next()){//檢測是否還有下一條記錄
int id = rs.getInt("id");
username = rs.getString("username");
password = rs.getString("password");
String mail = rs.getString("mail");
System.out.println(id+" "+username+" "+password+" "+mail);
}
}catch(Exception e){
e.printStackTrace();
}
// System.out.println(condition +"=?"+ username);
// System.out.println(condition_password +"=?"+ password);
if(condition.equals(username) && condition_password.equals(password)){
return true;
}
else{
return false;
}
}
用戶註冊:
用戶註冊也是需要條件的:用戶名密碼不爲空,用戶名在數據庫中不存在。
/**
* 查詢用戶 用戶不存在時允許註冊
* @param condition 查詢條件
*/
public boolean queryMember(String condition){
String username = null;
try{
Connection con = this.getConnection();
//定義SQL語句
String sql2 = "select * from user where username = ?";
PreparedStatement pstmt = con.prepareStatement(sql2);
//給每一個?佔位符指定數據
pstmt.setString(1, condition);
ResultSet rs = pstmt.executeQuery();//執行
System.out.println("id username password mail");
while(rs.next()){//檢測是否還有下一條記錄
int id = rs.getInt("id");
username = rs.getString("username");
String password = rs.getString("password");
String mail = rs.getString("mail");
System.out.println(id+" "+username+" "+password+" "+mail);
}
}catch(Exception e){
e.printStackTrace();
}
if(condition == username ){
return true;
}
else{
return false;
}
}
用戶修改個人資料等的功能將在後續加上。
附件是所有代碼的壓縮文件。