通过jdbc实现对数据库中数据的增删查改操作

Love The Way You Lie 2022-08-19 13:22 286阅读 0赞

###原始的东西该理解还是要理解


需要一个连接数据库的jar包(这里用的是MySQL):
http://download.csdn.net/detail/zhengyikuangge/9406895

直接上代码:

  1. public class ValueDao {
  2. public String DRIVER = "com.mysql.jdbc.Driver";
  3. //mysql驱动
  4. public String url = "jdbc:mysql://localhost/mysql";
  5. /*
  6. 数据库路径,localhost表示本地ip,如果使用的是默认端口号可以省略书写
  7. 端口号。如果要加端口号,则上述url改成:"jdbc:mysql://localhost:
  8. 3306/mysql"。 3306即为mysql默认的端口号
  9. */
  10. public String name = "root";
  11. //数据库的用户名
  12. public String psd = "abcefg";
  13. //数据库的密码
  14. public Connection conn;
  15. //声明数据库连接的变量
  16. public PreparedStatement ptmt;
  17. //声明预处理命令行的变量
  18. public ResultSet rs;
  19. //结果集变量
  20. class Student{
  21. String id;
  22. String name;
  23. } //测试对象,数据库表名,列名同上
  24. private void getConnection() throws Exception {
  25. Class.forName(DRIVER);
  26. //加载驱动
  27. conn = DriverManager.getConnection(url, name, psd);
  28. //获取连接
  29. }
  30. //添加数据
  31. private int insert(Student s) throws Exception {
  32. getConnection();
  33. String sql = "insert into xcx values(?,?)";
  34. ptmt = conn.prepareStatement(sql);
  35. ptmt.setString(1, s.id);
  36. ptmt.setString(2, s.name);
  37. int result = ptmt.executeUpdate();
  38. CloseAll();
  39. return result;
  40. //result表示影响的行数
  41. }
  42. //按照id获取数据,当然这里id应该只有一条数据,仅供参考
  43. private List<Student> select(String id) throws Exception {
  44. String s = null;
  45. getConnection();
  46. String sql = "select * from student where id = ? ";
  47. ptmt = conn.prepareStatement(sql);
  48. ptmt.setString(1, id);
  49. rs = ptmt.executeQuery();
  50. Student stu;
  51. List<Student> stus = new ArrayList<Student>();
  52. while (rs.next()) {
  53. stu = new Student();
  54. stu.id=rs.getString(1);
  55. stu.name=rs.getString(2);
  56. stus.add(stu);
  57. }
  58. closeAll();
  59. return stus;
  60. }
  61. //更新数据
  62. private int update(Student s) throws Exception {
  63. getConnection();
  64. String sql = "update student set name=? where id =?";
  65. ptmt = conn.prepareStatement(sql);
  66. ptmt.setString(1, s.id);
  67. int result = ptmt.executeUpdate();
  68. //result表示影响的行数
  69. CloseAll();
  70. return result;
  71. }
  72. //按照id删除数据
  73. private int delete(String id) throws Exception {
  74. getConnection();
  75. String sql = "delete from student where id = ?";
  76. ptmt = conn.prepareStatement(sql);
  77. ptmt.setString(1, id);
  78. int result = ptmt.executeUpdate();
  79. //result表示影响的行数
  80. CloseAll();
  81. return result;
  82. }
  83. private void closeAll() throws Exception {
  84. //这个方法就不用解释了。。
  85. if (stmt != null) {
  86. stmt.close();
  87. }
  88. if (ptmt != null) {
  89. ptmt.close();
  90. }
  91. if (conn != null) {
  92. conn.close();
  93. }
  94. }
  95. }

发表评论

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

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

相关阅读