学习Java,使用PreparedStatement实现到MySQL数据库的增删改查操作。作为测试项目,按照实际的MVC架构实现目录部署
项目已经share到 GitHub,有需要的可以clone测试。希望通过实际的编写代码能提高自己的编程能力
工程目录结构:

插入数据
public boolean addUser(Users users){
boolean bool = false;
conn = DbConn.getconn();
String sql = "insert into test_users(nickname, username, password, sex) values(?,?,?,?)";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, users.getNickname());
pstmt.setString(2, users.getUsername());
pstmt.setString(3, users.getPassword());
pstmt.setInt(4, users.getSex());
int rs = pstmt.executeUpdate();
if (rs > 0){
bool = true;
}
}catch (SQLException e){
e.printStackTrace();
}finally {
DbClose.addClose(pstmt, conn);
}
return bool;
}
查询
public String getUsers(Users users){
String result = null;
conn = DbConn.getconn();
String sql = "select * from test_users where username = ?";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, users.getUsername());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
result = "the user information is: " + rs.getString("nickname");
System.out.println(result);
}
}catch (SQLException e){
e.printStackTrace();
}finally {
DbClose.addClose(pstmt, conn);
}
return result;
}
更新
public boolean updatePasswd(Users user){
boolean bool = false;
Connection conn = DbConn.getconn();
String updatePasswd = "update test_users set password = ? where username = ?";
try {
pstmt = conn.prepareStatement(updatePasswd);
pstmt.setString(1, user.getPassword());
pstmt.setString(2, user.getUsername());
int rs = pstmt.executeUpdate();
if (rs > 0){
bool = true;
System.out.println("update password successfully!");
}
}catch (SQLException e) {
e.printStackTrace();
}finally {
DbClose.addClose(pstmt, conn);
}
return bool;
}
删除
public boolean deleteUsers(Users users){
boolean bool = false;
conn = DbConn.getconn();
String sql = "delete from test_users where username = ?";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, users.getUsername());
int rs = pstmt.executeUpdate();
if (rs > 0){
bool = true;
System.out.println("delete user successfully!");
}
}catch (SQLException e){
e.printStackTrace();
}finally {
DbClose.addClose(pstmt, conn);
}
return bool;
}
网友评论