Java从零开始(4)——入门项目

210 阅读1分钟

图书管理系统入门项目

登录功能实现

数据库:

创建用户表:

对应的实体类:

public class User {
	private int id;
	private String userName;
	private String password;}

添加set,get方法,构造器new时按照要求添加
方法

	public User login(Connection conn,User user ) throws Exception {
		User resUser = null;
		String sql = "select * from user where userName=? and password=?";
		PreparedStatement pt = conn.prepareStatement(sql);
		pt.setString(1, user.getUserName());
		pt.setString(2, user.getPassword());
		ResultSet res = pt.executeQuery();
		if(res.next()) {
			
			resUser = new User();
			resUser.setId(res.getInt("id"));
			resUser.setUserName(res.getString("userName"));
			resUser.setPassword(res.getString("password"));
		}
		return resUser;
				
	}

数据库连接

/**
	 * 数据库连接	
	 * @return
	 * @throws Exception
	 */
	public Connection getConn () throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn=DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
		return conn;}
	//关闭数据库
	public void closeConn(Connection conn)throws Exception{
		if(conn!=null)
			conn.close();
	}

创建图书表

实体类。。(各种省略)
添加图书:


public int add(Connection conn, Book book) throws Exception {
	String sql = "insert into book values (null,?,?,?,?,?)";
		PreparedStatement pmt = conn.prepareStatement(sql);
		pmt.setObject(1, book.getBookName());
		pmt.setObject(2, book.getAutor());
		pmt.setObject(3, book.getTotalStock());
		pmt.setObject(4, book.getPresentStock());
		pmt.setObject(5, book.getBookTypeUId());
		return pmt.executeUpdate();//返回改变记录数
	}

查询:

public ResultSet list(Connection conn,Book book) throws Exception {
	StringBuffer sb = new StringBuffer("select * from book,book_type where book.bookTypeId = book_type.id ");
	if(StringUtil.isNotEmpty(book.getBookName())) {		
    	sb.append("and book.bookName like '%"+book.getBookName()+"%'");
	}
	if(StringUtil.isNotEmpty(book.getAutor())) {
		sb.append("and book.autor like '%"+book.getAutor()+"%'");
	}
	if(book.getBookTypeUId()!=null&& book.getBookTypeUId()!=-1) {
		sb.append("and book.bookTypeId = "+book.getBookTypeUId());
	}
	PreparedStatement pmt=conn.prepareStatement(sb.toString());
	return pmt.executeQuery();//返回结果集	
}

删除图书:

public int delete(Connection conn ,String id)throws Exception{
	String sql = "delete from book where id = ?";
	PreparedStatement pmt = conn.prepareStatement(sql);
	pmt.setObject(1, id);
	return pmt.executeUpdate();//返回删除数
}

修改图书信息:

public int update(Connection conn , Book book)throws Exception{
	String sql = "update book set bookName = ?,autor = ?,bookTypeId = ? where id = ?";
	PreparedStatement pmt = conn.prepareStatement(sql);
	pmt.setObject(1, book.getBookName());
	pmt.setObject(2, book.getAutor());
	pmt.setObject(3, book.getBookTypeUId());
	pmt.setObject(4, book.getId());
	return pmt.executeUpdate();	//返回修改数		
}

图书管理简单的几个功能实现。!!

每天进步一点!!