5.28部落格

张佳木發表於2024-06-16

又是週一,那些殺不死我的還不如直接殺死我

學習內容:安卓

package com.example.app_02.utils;

import com.example.app_02.database.MySQLConnection;
import com.example.app_02.entity.User;
import com.example.app_02.entity.UserInfo;

public class UserDao extends MySQLConnection {
public User findUserName(String username) {
connect();
User user = null;
try {
//sql語句。我這裡是根據我自己的users表的username欄位來查詢記錄
String sql = "select * from user where username=?";
//獲取用於向資料庫傳送sql語句的preparedStatement
preparedStatement = connection.prepareStatement(sql);
//根據賬號進行查詢
preparedStatement.setString(1, username);
//執行sql查詢語句並返回結果集
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
//.next()表示指標先下一行,若有資料則返回true
user = new User();
user.setUsername(resultSet.getString("username"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
return user;//若傳入成功返回賬號,失敗則為null
}

public User findUser(String username, String password) {
connect();
User user = null;
try {
//sql語句。我這裡是根據我自己的users表的username和password欄位來查詢記錄
String sql = "select * from user where username=? and password=?";
//獲取用於向資料庫傳送sql語句的preparedStatement
preparedStatement = connection.prepareStatement(sql);
//根據賬號和密碼進行查詢
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
user = new User();
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
return user;//若傳入成功返回賬號和密碼,失敗則為null
}


public int registerUser(User user) {
int value = 0;
connect();
try {
String sql = "insert into user(username,password) values(?,?)";
preparedStatement = connection.prepareStatement(sql);
//將資料插入資料庫中
preparedStatement.setString(1, user.getUsername());
preparedStatement.setString(2, user.getPassword());
value = preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
return value;
}

public int updateUserStudentid(UserInfo userInfo, String username){
int value = 0;
connect();
try {
String sql = "update user set studentid=? where username=?";
preparedStatement = connection.prepareStatement(sql);
//將資料插入資料庫中
preparedStatement.setString(1, userInfo.getStudentid());
preparedStatement.setString(2, username);
value = preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
return value;
}
}