jdbc基础与工具类封装

谁践踏了优雅 2023-10-18 23:53 202阅读 0赞

我的网站:欢迎大家访问

aHR0cHM6Ly9zMi5heDF4LmNvbS8yMDE5LzA4LzEzL21DcWJaVC5wbmc

JDBC

概念

JDBC(Java DataBase Connectivity(Java数据库的连接)):

是一种用于执行SQL语句(DML,DDL,DQL)的Java API,可以为多种关系数据库(oracle,mysql,SQL server)提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序.

不管使用哪一种数据库,都需要去导入这个数据库给我们提供的jdbc实现的jar包

访问数据库的两种形式

1.JDBC最原生的方式去访问

2.使用第三方框架来进行访问(底层依然是JDBC)

JDBC连接数据库

导入相应的jar包

jdbc连接数据库步骤:贾琏欲执事

1.加载驱动

2.建立连接

3.获取语句

4.执行语句

5.关闭连接,释放资源

加载驱动三种方式

这里介绍最常用的一种:

  1. try {
  2. //第一步:通过反射加载驱动
  3. Class.forName("com.mysql.jdbc.Driver");
  4. //第二步:建立连接
  5. Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbcdemo","root","594395fzk");
  6. //第三步:获取语句对象,建表,书写sql语句
  7. Statement statement = conn.createStatement();
  8. String sql = "create table student(id bigint(20),name varchar(255),age int(10))";
  9. //第四步:执行sql语句
  10. //boolean b = statement.execute(sql);
  11. String ins = "insert into student (id,name,age) value ('02','电棍','2')";
  12. statement.executeUpdate(ins);
  13. //第五步:释放资源,关闭数据库连接
  14. statement.close();
  15. conn.close();
  16. } catch (Exception e) {
  17. // TODO Auto-generated catch block
  18. e.printStackTrace();
  19. }

至于其他两种:?????百度一下,你就知道

使用JDBC实现增删改查

  1. package com.ifueen.classtest.jdbcdemo;
  2. import static org.junit.Assert.*;
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8. import org.junit.After;
  9. import org.junit.Before;
  10. import org.junit.Test;
  11. public class JdbcConnect {
  12. Connection conn;
  13. Statement statement;
  14. @Before
  15. public void before() {
  16. try {
  17. //加载启动
  18. Class.forName("com.mysql.jdbc.Driver");
  19. //连接数据库
  20. conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbcdemo","root","594395fzk");
  21. } catch (Exception e) {
  22. // TODO Auto-generated catch block
  23. e.printStackTrace();
  24. }
  25. }
  26. /**
  27. * @throws Exception
  28. * 添加数据
  29. */
  30. @Test
  31. public void insert() throws Exception {
  32. String ins = "insert into student (id,name,age) values (5,'窦唯',20)";
  33. statement = conn.createStatement();
  34. statement.execute(ins);
  35. }
  36. /**
  37. * @throws Exception
  38. * 删除数据
  39. */
  40. @Test
  41. public void delete() throws Exception {
  42. String del = "delete from student where id=5";
  43. statement = conn.createStatement();
  44. statement.execute(del);
  45. }
  46. /**
  47. * @throws Exception
  48. * 更新数据
  49. */
  50. @Test
  51. public void update() throws Exception {
  52. String update = "update student set name='小小山泥若' where id=1";
  53. statement = conn.createStatement();
  54. statement.executeUpdate(update);
  55. }
  56. /**
  57. * @throws Exception
  58. * 查询数据
  59. */
  60. @Test
  61. public void select() throws Exception {
  62. String select = "select * from student";
  63. statement = conn.createStatement();
  64. ResultSet resultSet = statement.executeQuery(select);
  65. while(resultSet.next()){
  66. System.out.println(resultSet.getString("name"));
  67. }
  68. }
  69. /**
  70. * @throws SQLException
  71. * 关闭连接,释放资源
  72. */
  73. @After
  74. public void after() throws SQLException{
  75. statement.close();
  76. conn.close();
  77. }
  78. }

封装JDBC工具类

为了更方便,让代码使用起来更高效,可以将连接数据库的操作封装成一个工具类,以后在每次要进行数据库连接的时候直接使用工具类即可

这里先将数据库的驱动连接,url,账户密码等放在了资源文件夹的properties文件中

资源文件db.properties:

  1. driverClassName=com.mysql.jdbc.Driver
  2. url=jdbc:mysql://127.0.0.1:3306/jdbcwork
  3. username=root
  4. password=594395fzk

封装的工具类:

  1. package com.ifueen.classtest.util;
  2. import java.io.IOException;
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8. import java.util.Properties;
  9. public class JDBCUtil {
  10. //创建单例模式
  11. private static JDBCUtil instance;
  12. private JDBCUtil() {
  13. }
  14. public static JDBCUtil getinstance() {
  15. return instance;
  16. }
  17. private static Properties prop = new Properties();
  18. //静态代码块,存放要优先加载的功能语句
  19. static{
  20. try {
  21. //通过字节码来获取流
  22. prop.load(JDBCUtil.class.getResourceAsStream("/db.properties"));
  23. } catch (IOException e1) {
  24. // TODO Auto-generated catch block
  25. e1.printStackTrace();
  26. }
  27. instance = new JDBCUtil();
  28. try {
  29. //加载驱动
  30. Class.forName(prop.getProperty("driverClassName"));
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. /**
  36. * @return
  37. * 连接数据库的方法
  38. */
  39. public Connection getconn() {
  40. Connection conn = null;
  41. try {
  42. //连接数据库
  43. conn = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("username"), prop.getProperty("password"));
  44. } catch (Exception e) {
  45. // TODO Auto-generated catch block
  46. e.printStackTrace();
  47. }
  48. return conn;
  49. }
  50. /**
  51. *
  52. * 关闭连接,释放资源
  53. */
  54. public void getclose(ResultSet rs, Statement st, Connection conn) {
  55. try {
  56. if (rs != null)
  57. rs.close();
  58. } catch (SQLException e) {
  59. // TODO Auto-generated catch block
  60. e.printStackTrace();
  61. } finally {
  62. try {
  63. if (st != null)
  64. st.close();
  65. } catch (SQLException e) {
  66. // TODO Auto-generated catch block
  67. e.printStackTrace();
  68. } finally {
  69. try {
  70. if (conn != null)
  71. conn.close();
  72. } catch (SQLException e) {
  73. // TODO Auto-generated catch block
  74. e.printStackTrace();
  75. }
  76. }
  77. }
  78. }
  79. public void getclose(Statement st, Connection conn) {
  80. try {
  81. if(st!=null)
  82. st.close();
  83. } catch (SQLException e) {
  84. // TODO Auto-generated catch block
  85. e.printStackTrace();
  86. }finally {
  87. if(conn!=null)
  88. try {
  89. conn.close();
  90. } catch (SQLException e) {
  91. // TODO Auto-generated catch block
  92. e.printStackTrace();
  93. }
  94. }
  95. }
  96. }

这下连接数据库的操作就很好地封装成了一个工具类,只需要在要进行操作的地方使用即可

测试类:

  1. package com.ifueen.classtest.util;
  2. import static org.junit.Assert.*;
  3. import java.sql.Connection;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. import org.junit.Test;
  8. public class UtilTest {
  9. @Test
  10. public void test() throws Exception {
  11. //调用封装好的加载驱动的方法
  12. Connection conn = JDBCUtil.getinstance().getconn();
  13. Statement st = conn.createStatement();
  14. String sql = "select * from student";
  15. ResultSet rs = st.executeQuery(sql);
  16. while (rs.next()) {
  17. System.out.println(rs.getString("name"));
  18. }
  19. //调用关闭驱动的方法
  20. JDBCUtil.getinstance().getclose(rs, st, conn);
  21. }
  22. }

Dao层的实现

DAO : 主要是用来做数据库的操作
模块化,分工明确,解耦(责任分离)

刚才已经说到要分层,各层之间相互调用,现在数据层 调用 数据库,需要传什么内容?
比如 要添加一个用户,怎么添加?

界面层:收集数据; name,password,age…等等 需要传递很多东西;
业务层:界面层收集之后,传到业务层;

在这里插入图片描述
因为我们没有前端传过来的数据,现在只使用dao,domian层来进行crud操作

大体结构如下
在这里插入图片描述

首先肯定要在数据库中将表建好,然后写一个javabean类和这张表一一对应

在这里插入图片描述

domian层下面的javabean类:

  1. package com.ifueen.homework.domian;
  2. public class Student {
  3. private long id;
  4. private String username;
  5. private String password;
  6. private int age;
  7. private boolean sex;
  8. private String intro;
  9. public long getId() {
  10. return id;
  11. }
  12. public void setId(long id) {
  13. this.id = id;
  14. }
  15. public String getUsername() {
  16. return username;
  17. }
  18. public void setUsername(String username) {
  19. this.username = username;
  20. }
  21. public String getPassword() {
  22. return password;
  23. }
  24. public void setPassword(String password) {
  25. this.password = password;
  26. }
  27. public int getAge() {
  28. return age;
  29. }
  30. public void setAge(int age) {
  31. this.age = age;
  32. }
  33. public boolean isSex() {
  34. return sex;
  35. }
  36. public void setSex(boolean sex) {
  37. this.sex = sex;
  38. }
  39. public String getIntro() {
  40. return intro;
  41. }
  42. public void setIntro(String intro) {
  43. this.intro = intro;
  44. }
  45. public Student(long id, String username, String password, int age, boolean sex, String intro) {
  46. super();
  47. this.id = id;
  48. this.username = username;
  49. this.password = password;
  50. this.age = age;
  51. this.sex = sex;
  52. this.intro = intro;
  53. }
  54. public Student(Long id,String username) {
  55. super();
  56. this.username = username;
  57. this.id = id;
  58. }
  59. public Student() {
  60. super();
  61. }
  62. }

Dao类:

  1. package com.ifueen.homework.dao;
  2. import com.ifueen.homework.domian.Student;
  3. public interface StudentDao {
  4. //增加数据
  5. void add(Student s);
  6. //删除数据
  7. void delete(long id);
  8. //修改数据
  9. void update(Student s);
  10. //查找数据
  11. Student select(Student s);
  12. //查找数据2
  13. void select(Long id);
  14. }

dao的实现类

  1. package com.ifueen.homework.dao.impl;
  2. import java.sql.Connection;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import com.ifueen.classtest.util.JDBCUtil;
  7. import com.ifueen.homework.dao.StudentDao;
  8. import com.ifueen.homework.domian.Student;
  9. import com.sun.javafx.binding.Logging;
  10. public class StudentDaoImpl implements StudentDao{
  11. /**
  12. * 新增数据
  13. */
  14. @Override
  15. public void add(Student s) {
  16. // TODO Auto-generated method stub
  17. try {
  18. //加载驱动,连接数据库
  19. Connection conn = JDBCUtil.getinstance().getconn();
  20. //得到Statement对象
  21. Statement st = conn.createStatement();
  22. //写sql语句
  23. String sql = "insert into student(id,username,password,age,sex,intro) "
  24. + "values ('"+s.getId()+"','"+s.getUsername()+"','"+s.getPassword()+"','"+s.getAge()+"','"+s.isSex()+"','"+s.getIntro()+"')";
  25. //执行sql语句
  26. st.execute(sql);
  27. //关闭连接,释放资源
  28. JDBCUtil.getinstance().getclose(st, conn);
  29. } catch (SQLException e) {
  30. // TODO Auto-generated catch block
  31. e.printStackTrace();
  32. }
  33. }
  34. /**
  35. * 删除数据
  36. */
  37. @Override
  38. public void delete(long id) {
  39. // TODO Auto-generated method stub
  40. try {
  41. Connection conn = JDBCUtil.getinstance().getconn();
  42. Statement st = conn.createStatement();
  43. String sql = "delete from student where id="+id;
  44. st.execute(sql);
  45. JDBCUtil.getinstance().getclose(st, conn);
  46. } catch (SQLException e) {
  47. // TODO Auto-generated catch block
  48. e.printStackTrace();
  49. }
  50. }
  51. /**
  52. * 修改数据
  53. */
  54. @Override
  55. public void update(Student s) {
  56. // TODO Auto-generated method stub
  57. try {
  58. Connection conn = JDBCUtil.getinstance().getconn();
  59. Statement st = conn.createStatement();
  60. String sql = "update student set username='"+s.getUsername()+"' where id="+s.getId();
  61. st.executeUpdate(sql);
  62. JDBCUtil.getinstance().getclose(st, conn);
  63. } catch (SQLException e) {
  64. // TODO Auto-generated catch block
  65. e.printStackTrace();
  66. }
  67. }
  68. /**
  69. * 查询数据1
  70. */
  71. @Override
  72. public Student select(Student s) {
  73. Student student = null;
  74. // TODO Auto-generated method stub
  75. try {
  76. Connection conn = JDBCUtil.getinstance().getconn();
  77. Statement st = conn.createStatement();
  78. String sql = "select * from student";
  79. ResultSet set = st.executeQuery(sql);
  80. student = new Student();
  81. while (set.next()) {
  82. student.setId(set.getLong("id"));
  83. student.setUsername(set.getString("username"));
  84. student.setPassword(set.getString("password"));
  85. student.setAge(set.getInt("age"));
  86. student.setSex(set.getBoolean("sex"));
  87. student.setIntro(set.getString("intro"));
  88. }
  89. JDBCUtil.getinstance().getclose(st, conn);
  90. } catch (SQLException e) {
  91. // TODO Auto-generated catch block
  92. e.printStackTrace();
  93. }
  94. return student;
  95. }
  96. /**
  97. * 查询数据2
  98. * 全部循环打印显示出来
  99. */
  100. @Override
  101. public void select(Long id) {
  102. Student student = null;
  103. // TODO Auto-generated method stub
  104. try {
  105. Connection conn = JDBCUtil.getinstance().getconn();
  106. Statement st = conn.createStatement();
  107. String sql = "select * from student where id="+id;
  108. ResultSet set = st.executeQuery(sql);
  109. student = new Student();
  110. while (set.next()) {
  111. System.out.print(set.getLong("id")+" ");
  112. System.out.print(set.getString("username")+" ");
  113. System.out.print(set.getString("password")+" ");
  114. System.out.print(set.getInt("age")+" ");
  115. System.out.print(set.getBoolean("sex")+" ");
  116. System.out.print(set.getString("intro")+" ");
  117. }
  118. JDBCUtil.getinstance().getclose(st, conn);
  119. } catch (SQLException e) {
  120. // TODO Auto-generated catch block
  121. e.printStackTrace();
  122. }
  123. }
  124. }

最后测试类:

  1. package com.ifueen.homework.test;
  2. import static org.junit.Assert.*;
  3. import java.sql.Connection;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import org.junit.Before;
  7. import org.junit.Test;
  8. import com.ifueen.classtest.util.JDBCUtil;
  9. import com.ifueen.homework.dao.StudentDao;
  10. import com.ifueen.homework.dao.impl.StudentDaoImpl;
  11. import com.ifueen.homework.domian.Student;
  12. public class StudentTest {
  13. StudentDao std = new StudentDaoImpl();
  14. /**
  15. * 添加数据
  16. */
  17. @Test
  18. public void add() {
  19. Student student = new Student(1,"山泥若","123456",25,true,"我顶不住了");
  20. std.add(student);
  21. }
  22. /**
  23. * 删除数据
  24. */
  25. @Test
  26. public void delete() {
  27. std.delete(1L);
  28. }
  29. /**
  30. * 修改数据
  31. */
  32. @Test
  33. public void update() {
  34. Student student = new Student(2L,"落日飞车");
  35. std.update(student);
  36. }
  37. /**
  38. * 查询数据
  39. */
  40. @Test
  41. public void select() {
  42. Student student = new Student(1,"山泥若","123456",25,true,"我顶不住了");
  43. //拿到查询的结果
  44. Student select = std.select(student);
  45. System.out.println(select.getUsername());
  46. System.out.println(select.getIntro());
  47. }
  48. /**
  49. * 查询数据2
  50. */
  51. @Test
  52. public void selects() {
  53. std.select(1L);
  54. }
  55. }

发表评论

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

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

相关阅读

    相关 jdbc 工具

    最近写了一个jdbc工具类,拿出来献丑了,最近数据库配置都喜欢放在配置文件,我的这个也是。这么做的优势就是,当你去换数据库的时候不用改动代码,例如去现场环境部署代码,和你在测试