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();
//sql语句
String sql = "select * from user where username= ? and password = ?";
pstmt = connection.prepareStatement(sql);
//给通配符赋值
pstmt.setString(1, user);
pstmt.setString(2, password);
resultSet = pstmt.executeQuery();
//注意: 这里表中只有两种情况,有这个用户或者没有,直接用resultset。next()即可
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();
}
}
}
}
}
|
|