利用java实现数据库增删查改(dao层)

本文介绍了如何使用Java进行数据库的基本操作,包括根据书名和作者查找书籍,向借阅表中添加记录,通过用户ID和书ID删除借阅信息,以及更新管理员的电话号码。这些操作都利用了PreparedStatement进行SQL语句的预编译,提高了代码的安全性和效率。
摘要由CSDN通过智能技术生成

查找

public Books inquire(String bookName, String bookAuthor) {
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnnection();
            String sql = "select * from book where bookName=? and author=?";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, bookName);
            pstm.setString(2, bookAuthor);
            rs = pstm.executeQuery();
            if (rs.next()) {
                return new Books(rs.getString("bookName"), rs.getString("author"),
                        rs.getString("bookType"), rs.getInt("bookNumber"),
                        rs.getInt("id"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(rs, pstm, conn);
        }
        return null;
    }

添加

public void addLend(int userId, int bookId) {
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnnection();
            String sql = "insert lendBooks (userId,bookId) values (?,?)";
            pstm = conn.prepareStatement(sql);
            pstm.setInt(1, userId);
            pstm.setInt(2, bookId);
            pstm.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(null, pstm, conn);
        }
    }

删除

public void userIdClear(int userId, int bookId) {
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnnection();
            String sql = "delete from lendBooks where userId=? and bookId=?";
            pstm=conn.prepareStatement(sql);
             pstm.setInt(1,userId);
             pstm.setInt(2,bookId);
             pstm.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.close(null,pstm,conn);
        }

修改

 public void update(String account, String newPhoneNum) {
        Connection conn = null;
        ResultSet rs = null;
        PreparedStatement pstm = null;
        try {
            conn = JdbcUtils.getConnnection();
            String sql = "select * from manager where account=?";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, account);
            rs = pstm.executeQuery();
            while (rs.next()) {
                String sql1 = "update manager set telephone=? where account=?";
                pstm = conn.prepareStatement(sql1);
                pstm.setString(1, newPhoneNum);
                pstm.setString(2, account);
                pstm.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(rs, pstm, conn);
        }
    }
CP30是一个开源的JDBC连接池,它可以更好地管理数据库连接。下面给出一个使用CP30实现数据库增删查改的示例代码。 首先,需要在pom.xml中添加CP30的依赖: ```xml <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> </dependency> ``` 然后,创建一个DBUtil类,用于创建和管理连接池: ```java import com.mchange.v2.c3p0.ComboPooledDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBUtil { private static DataSource dataSource; static { dataSource = new ComboPooledDataSource("mysql"); } public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } public static void close(Connection conn, Statement stmt, ResultSet rs) { try { if (rs != null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (stmt != null) { stmt.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } } } ``` 接下来,可以创建一个User类,用于表示数据库中的一条记录: ```java public class User { private int id; private String name; private int age; public User(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` 然后,可以创建一个UserDAO类,用于实现数据库增删查改: ```java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class UserDAO { public void addUser(User user) { Connection conn = null; PreparedStatement stmt = null; try { conn = DBUtil.getConnection(); stmt = conn.prepareStatement("INSERT INTO user(name, age) VALUES (?, ?)"); stmt.setString(1, user.getName()); stmt.setInt(2, user.getAge()); stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(conn, stmt, null); } } public void deleteUser(int id) { Connection conn = null; PreparedStatement stmt = null; try { conn = DBUtil.getConnection(); stmt = conn.prepareStatement("DELETE FROM user WHERE id = ?"); stmt.setInt(1, id); stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(conn, stmt, null); } } public void updateUser(User user) { Connection conn = null; PreparedStatement stmt = null; try { conn = DBUtil.getConnection(); stmt = conn.prepareStatement("UPDATE user SET name = ?, age = ? WHERE id = ?"); stmt.setString(1, user.getName()); stmt.setInt(2, user.getAge()); stmt.setInt(3, user.getId()); stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(conn, stmt, null); } } public List<User> getUsers() { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; List<User> users = new ArrayList<>(); try { conn = DBUtil.getConnection(); stmt = conn.prepareStatement("SELECT * FROM user"); rs = stmt.executeQuery(); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); User user = new User(id, name, age); users.add(user); } } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(conn, stmt, rs); } return users; } } ``` 最后,可以在Main类中测试以上的代码: ```java public class Main { public static void main(String[] args) { UserDAO dao = new UserDAO(); // 添加一条记录 dao.addUser(new User(1, "张三", 20)); // 更新一条记录 dao.updateUser(new User(1, "李四", 21)); // 删除一条记录 dao.deleteUser(1); // 查询所有记录 List<User> users = dao.getUsers(); for (User user : users) { System.out.println(user.getId() + " " + user.getName() + " " + user.getAge()); } } } ``` 以上代码实现了使用CP30连接池的数据库增删查改
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值