package cn.pzhu.dao.impl;
import cn.pzhu.dao.UserDAO;
import cn.pzhu.pojo.User;
import cn.pzhu.util.JDBCUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class UserDAOImpl implements UserDAO {
@Override
public int insert(User user) {
Connection con =JDBCUtil.getConnection();
PreparedStatement preparedStatement =null;
ResultSet resultSet=null;
try {
String sql ="INSERT INTO `user` VALUES(NULL,?,?)";
preparedStatement=con.prepareStatement(sql);
preparedStatement.setString(1, user.getUsername());
preparedStatement.setString(2, user.getPassword());
preparedStatement.execute();
return 1;
} catch (SQLException e) {
e.printStackTrace();
return 0;
}finally {
JDBCUtil.close(null,preparedStatement,con);
}
}
@Override
public int delete(String s) {
Connection con =JDBCUtil.getConnection();
PreparedStatement preparedStatement =null;
ResultSet resultSet=null;
try {
String sql ="delete from user where username =?";
assert con != null;
preparedStatement=con.prepareStatement(sql);
preparedStatement.setString(1,s);
preparedStatement.execute();
return 1;
} catch (SQLException e) {
e.printStackTrace();
return 0;
}finally {
JDBCUtil.close(null,preparedStatement,con);
}
}
@Override
public int update(User user) {
Connection con =JDBCUtil.getConnection();
PreparedStatement preparedStatement =null;
ResultSet resultSet=null;
try {
String sql ="update user set password=? where username=?";
assert con != null;
preparedStatement=con.prepareStatement(sql);
preparedStatement.setString(1, user.getPassword());
preparedStatement.setString(2, user.getUsername());
preparedStatement.execute();
return 1;
} catch (SQLException e) {
e.printStackTrace();
return 0;
}finally {
JDBCUtil.close(null,preparedStatement,con);
}
}
@Override
public User selectById(String s) {
Connection con = JDBCUtil.getConnection();
PreparedStatement preparedStatement =null;
ResultSet resultSet=null;
User resUser = new User();
try {
String sql= "select * from user where username=?";
preparedStatement=con.prepareStatement(sql);
preparedStatement.setString(1,s);
resultSet=preparedStatement.executeQuery();
// System.out.print(resultSet);
if(resultSet.next()){
String name=resultSet.getString("username");
String password =resultSet.getString("password");
resUser.setPassword(password);
resUser.setUsername(name);
}
}catch (Exception e){
e.printStackTrace();
return null;
}finally {
JDBCUtil.close(resultSet,preparedStatement,con);
}
return resUser;
}
@Override
public List<User> selectAll() {
return null;
}
}