public class DaoImpl implements Dao {
@Override
public boolean login(String user, String password) {
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet resultSet = null;
try {
connection = JDBCUtils.getConnection();
String sql = "select * from user where username= ? and password = ?";
pstmt = connection.prepareStatement(sql);
pstmt.setString(1, user);
pstmt.setString(2, password);
resultSet = pstmt.executeQuery();
return resultSet.next();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return false;
}
@Override
public void regiest(String user, String password) {
if (user == null || password == null) {
System.out.println("用户名或者密码不能为空");
}
Connection connection = null;
PreparedStatement pstmt = null;
try {
connection = JDBCUtils.getConnection();
String sql0 = "select * from user where username = ? ";
PreparedStatement pstmt1 = connection.prepareStatement(sql0);
pstmt1.setObject(1, user);
ResultSet rs = pstmt1.executeQuery();
//判断是否有用户名相同
if (rs.next()) {
System.out.println("用户注册失败,用户名已存在");
} else {
String sql = "insert into user values(null,?,?)";
pstmt = connection.prepareStatement(sql);
pstmt.setString(1, user);
pstmt.setString(2, password);
int i = pstmt.executeUpdate();
if (i < 0) {
System.out.println("注册失败");
} else {
System.out.println("注册成功");
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
} |
|