安卓图书管理系统服务端userdao
时间: 2023-09-16 17:16:21 浏览: 50
以下是一个简单的安卓图书管理系统服务端中userdao的示例代码,用于与数据库进行交互:
```
import java.sql.*;
public class UserDao {
private Connection conn = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
// 连接数据库
public void getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/book_management_system";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
}
// 关闭数据库连接
public void closeConnection() {
try {
if(rs != null) {
rs.close();
}
if(ps != null) {
ps.close();
}
if(conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 添加用户
public boolean addUser(User user) {
try {
getConnection();
String sql = "INSERT INTO user (username, password, name, email) VALUES (?, ?, ?, ?)";
ps = conn.prepareStatement(sql);
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ps.setString(3, user.getName());
ps.setString(4, user.getEmail());
int result = ps.executeUpdate();
if(result > 0) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection();
}
return false;
}
// 根据用户名查找用户
public User getUserByUsername(String username) {
User user = null;
try {
getConnection();
String sql = "SELECT * FROM user WHERE username = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
rs = ps.executeQuery();
if(rs.next()) {
user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setName(rs.getString("name"));
user.setEmail(rs.getString("email"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection();
}
return user;
}
}
```
该示例代码使用了JDBC来连接MySQL数据库,并提供了添加用户和根据用户名查找用户的操作。在实际使用中,需要根据具体的需求进行修改和完善。