JDBC连接数据库实现增删改查,我连接成功了但是没有运行成功,我想要一份关于这个连接后的代码
3条回答 默认 最新
一起看海呦 2023-05-28 01:19关注java
// 加载数据库驱动 Class.forName("com.mysql.jdbc.Driver"); // 连接数据库 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456"); // 查询数据 Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from user"); while (rs.next()) { System.out.println(rs.getString("name")); } // 新增数据 PreparedStatement pstmt = conn.prepareStatement("insert into user(name, age) values (?, ?)"); pstmt.setString(1, "张三"); pstmt.setInt(2, 30); pstmt.executeUpdate(); // 修改数据 pstmt = conn.prepareStatement("update user set age=? where name=?"); pstmt.setInt(1, 35); pstmt.setString(2, "张三"); pstmt.executeUpdate(); // 删除数据 pstmt = conn.prepareStatement("delete from user where name=?"); pstmt.setString(1, "张三"); pstmt.executeUpdate(); // 关闭连接 conn.close();解决 无用评论 打赏 举报