增删改查

╰+攻爆jí腚メ 2022-08-09 00:46 509阅读 0赞
  1. package cn.itcast.jdbc;
  2. import java.sql.Connection;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. public class CRUD {
  7. public static void main(String[] args) {
  8. }
  9. static void create() throws SQLException {
  10. Connection conn = null;
  11. Statement st = null;
  12. ResultSet rs = null;
  13. try {
  14. conn = JdbcUtils.getConnection();
  15. st = conn.createStatement();
  16. String sql = "insert into user(name,birthday,money)values('name1','1987-1-1',400)";
  17. int i = st.executeUpdate(sql);
  18. System.out.println("i=" + i);
  19. } finally {
  20. JdbcUtils.free(rs, st, conn);
  21. }
  22. }
  23. static void read() throws SQLException {
  24. Connection conn = null;
  25. Statement st = null;
  26. ResultSet rs = null;
  27. try {
  28. conn = JdbcUtils.getConnection();
  29. st = conn.createStatement();
  30. rs = st.executeQuery("select id,name,birthday,money from user");
  31. while (rs.next()) {
  32. System.out.println("id:" + rs.getObject("id") + "\tname:"
  33. + rs.getObject("name") + "\tbirthday:"
  34. + rs.getObject("birthday") + "\tmoney:"
  35. + rs.getObject("money"));
  36. }
  37. } finally {
  38. JdbcUtils.free(rs, st, conn);
  39. }
  40. }
  41. static void update() throws SQLException {
  42. Connection conn = null;
  43. Statement st = null;
  44. ResultSet rs = null;
  45. try {
  46. conn = JdbcUtils.getConnection();
  47. st = conn.createStatement();
  48. String sql = "update user set money=money+10";
  49. int i = st.executeUpdate(sql);
  50. System.out.println("i=" + i);
  51. } finally {
  52. JdbcUtils.free(rs, st, conn);
  53. }
  54. }
  55. static void delete() throws SQLException {
  56. Connection conn = null;
  57. Statement st = null;
  58. ResultSet rs = null;
  59. try {
  60. conn = JdbcUtils.getConnection();
  61. st = conn.createStatement();
  62. String sql = "delete from user where id>=4";
  63. int i = st.executeUpdate(sql);
  64. System.out.println("i=" + i);
  65. } finally {
  66. JdbcUtils.free(rs, st, conn);
  67. }
  68. }
  69. }

用到的工具类JdbcUtils.java
增删改查中就查比较麻烦一点,增删改都比较简单

发表评论

表情:
评论列表 (有 0 条评论,509人围观)

还没有评论,来说两句吧...

相关阅读