Java-查询数据库

开发工具与关键技术:java
作者:张俊辉
撰写时间:2019年6月18日

后台中写查询方法例如:根据账号查询用户表(SYS_User),首先需要一个储存用户表的实体类(UserPo),与数据库字段对应声明对应类型对应字段的私有变量,对应变量的获取方法与赋值方法,如下:

public class UserPo {
	private int userID; 
	private String userName;
	private String userNum;
	private String password;
	private boolean state; 
	private int userTypeID;
	public int getUserID() {
		return userID;
	}
	public void setUserID(int userID) {
		this.userID = userID;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserNum() {
		return userNum;
	}
	public void setUserNum(String userNum) {
		this.userNum = userNum;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public boolean getState() {
		return state;
	}
	public void setState(boolean state) {
		this.state = state;
	}
	public int getUserTypeID() {
		return userTypeID;
	}
	public void setUserTypeID(int userTypeID) {
		this.userTypeID = userTypeID;
	}
}

然后声明一个接口(IUserDao)写入登录查询方法:public UserPo Login(String userNum);
声明一个类实现接口IUserDao,声明一个String变量存放数据库查询查询语句,声明一个Connection变量存放数据库连接(数据库连接方法可参考:Java连接数据库),声明一个PreparedStatement变量执行查询语句,声明一个ResultSet变量获取数据库查询的数据,代码如下:

public class UserDaoImpl implements IUserDao{
	private String login="select * from SYS_User where userNum=?";
	private Connection conn =null;
	private PreparedStatement ps=null;
	private ResultSet rs=null;
	@Override
	public UserPo Login(String userNum) {
		UserPo userPo=null;
		try {
			conn=DBUtil.getConnection();
			ps=conn.prepareStatement(login);
			ps.setString(1, userNum);
			rs= ps.executeQuery();
			while (rs.next()) {
				userPo=new UserPo();
				userPo.setPassword(rs.getString("Password"));
				userPo.setState(rs.getBoolean("State"));
				userPo.setUserID(rs.getInt("UserID"));
				userPo.setUserName(rs.getString("UserName"));
				userPo.setUserNum(rs.getString("UserNum"));
				userPo.setUserTypeID(rs.getInt("UserTypeID"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DBUtil.close(conn, ps, rs);
		}
		return userPo;
	}
}

你可能感兴趣的:(专题技术)