BookDaoImpl
package com.zhongruan.dao.impl;
import com.zhongruan.DBUil.DBUtil;
import com.zhongruan.dao.IBookDao;
import com.zhongruan.model.Book;
import com.zhongruan.model.User;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class BookDaoImpl implements IBookDao {
public Book findUsernameByUsername(String username){
ResultSet resultSet = null;
PreparedStatement statement = null;
Connection connection = null;
Book book=null;
try {
connection= DBUtil.getConnection();
String sql = “select * from tb_user where username=?”;
statement=connection.prepareStatement(sql);
statement.setString(1,username);
resultSet=statement.executeQuery();
while (resultSet.next()){
book = new Book();
book.setUsername(resultSet.getString(2));
book.setPassword(resultSet.getString(3));
//user.setType(resultSet.getInt(4));
}
} catch(ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.closeAll(resultSet,statement,connection);
}
return book;
}
@Override
public List<Book> findAll() {
List<Book> books=new ArrayList<>();
PreparedStatement statement=null;
ResultSet resultSet=null;
Connection connection=null;
try {
connection = DBUtil.getConnection();
String sql="select * from tb_user";
statement=connection.prepareStatement(sql);
resultSet=statement.executeQuery();
while (resultSet.next()){
Book book=new Book();
book.setId(resultSet.getInt(1));
book.setUsername(resultSet.getString(2));
book.setPassword(resultSet.getString(3));
books.add(book);
}
}
catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.closeAll(resultSet,statement,connection);
}
return books;
}
public void delete(int id){
PreparedStatement statement=null;
Connection connection=null;
try {
connection=DBUtil.getConnection();
statement=connection.prepareStatement("delete from tb_user where id=?");
statement.setInt(1,id);
statement.executeUpdate();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
DBUtil.closeAll(null,statement,connection);
}
}
public void insert(String username,String password){
PreparedStatement statement=null;
Connection connection=null;
try {
connection=DBUtil.getConnection();
String sql="insert into tb_user(username, password) values(?,?)";
statement=connection.prepareStatement(sql);
statement.setString(1,username);
statement.setString(2,password);
statement.executeUpdate();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
DBUtil.closeAll(null,statement,connection);
}
}
public Book findBookById(int id){
Book book = null;
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = DBUtil.getConnection();
//3写sql
String sql = "select * from tb_user where id=?";
statement = connection.prepareStatement(sql);
statement.setInt(1, id);
resultSet = statement.executeQuery();
while (resultSet.next()) {
book = new Book();
book.setId(resultSet.getInt(1));
book.setUsername