• JDBC2


    目录

    后端三层架构

    JDBC封装

    数据库连接池:

    Druid的使用

    DButils使用

    QueryRunner 方法:

     query:

      update:

    ResultSetHandler:

    BeanListHandler:

    ScalarHandler:


    后端三层架构

    controlle:作用与前端交互

                                            如:获取前端数据,给前端响应数据

    sercer:作用处理业务

    dao:作用操作数据库

    建立项目时可以创建这几个包

                    controlle:前端相关

                    server:业务处理           如:main

                    dao:操作数据库        如:使用DQL,DML操作语句

                    bean:对应实体    如:用户类

                    utils:工具类        如:配置文件,封装的数据库连接

    JDBC封装

            在编写代码时需要重复的连接关闭数据库,导致了大量代码冗余,此时可以将其封装到一个类中,并提供静态方法

            从上个JDBC1博客看例子,Connection对象需要重复使用,关闭也需要重复关闭,而配置代码也写在了此代码中,将其全部分开,可以使代码更加简洁。

    将其写进一个 MyconnectionUtils类

    1. import java.io.IOException;
    2. import java.io.InputStream;
    3. import java.sql.*;
    4. import java.util.Properties;
    5. public class MyconnectionUtils {
    6. static {//静态只在类加载时加载一次
    7. try {
    8. Class.forName("com.mysql.jdbc.Driver");
    9. }catch (ClassNotFoundException e){
    10. e.printStackTrace();
    11. }
    12. }
    13. public static Connection getConnection() throws IOException, SQLException {
    14. //提供connection对象
    15. InputStream is =MyconnectionUtils.class.getResourceAsStream("Dbinfo.properties");
    16. //输入流,读取根目录下的Dbinfo.properties
    17. Properties properties = new Properties();//使用Properties来读取配置内容
    18. //Properties 可以读取字典内容,如下相当于用键读值
    19. properties.load(is);
    20. String url = properties.getProperty("URL");
    21. String username = properties.getProperty("USER");
    22. String password = properties.getProperty("PASSMI");
    23. Connection connection = DriverManager.getConnection(url, username, password);
    24. return connection;//返回connection
    25. }
    26. public static void Close(ResultSet resultSet,Statement statement, Connection connection) throws SQLException {
    27. //用来关闭
    28. if (resultSet != null && ! resultSet.isClosed()){
    29. resultSet.close();//关闭结果
    30. }
    31. if (statement != null && !statement.isClosed()){
    32. statement.close();//关闭提交
    33. }
    34. if (connection != null && !connection.isClosed()){
    35. connection.close();//关闭连接
    36. }
    37. }
    38. }
    Dbinfo.properties  文件内容:

    使用:使用时直接用类名调用其静态方法

    1. import java.io.IOException;
    2. import java.sql.*;
    3. public class Main {
    4. public static void main(String[] args) {
    5. Connection connection = null;
    6. try {
    7. connection = MyconnectionUtils.getConnection();
    8. } catch (IOException e) {
    9. e.printStackTrace();
    10. } catch (SQLException e) {
    11. e.printStackTrace();
    12. }
    13. try {
    14. connection.setAutoCommit(false);//关闭自动提交
    15. String sql1="update yinhang set u_age=u_age+10 where u_id= ?";
    16. PreparedStatement statement = connection.prepareStatement(sql1);
    17. statement.setInt(1,1);
    18. statement.executeUpdate();
    19. String sql2="update yinhang set u_age=u_age-10 where u_id= ?";
    20. PreparedStatement statement2 = connection.prepareStatement(sql2);
    21. statement2.setInt(1,2);//
    22. statement2.executeUpdate();
    23. connection.commit();//提交执行
    24. MyconnectionUtils.Close(null,statement,null);
    25. MyconnectionUtils.Close(null,statement2,connection);//关闭资源
    26. } catch (Exception e) {
    27. try {
    28. connection.rollback();//出现任何错误直接回滚,保证数据安全
    29. } catch (SQLException ex) {
    30. ex.printStackTrace();
    31. }
    32. }finally {
    33. try{
    34. if(connection != null&& connection.isClosed()){
    35. connection.setAutoCommit(true);//变回自动提交
    36. }
    37. }catch (SQLException e){
    38. e.printStackTrace();
    39. }
    40. }
    41. }
    42. }

    getResourceAsStream方法

                    如果最前面是正斜杆/,那么则从项目根目录开始查找

                    如果不加正斜杆/,那么则从该方法的调用者class所在的目录查找。

    数据库连接池

    作用:存储与管理数据库连接,帮助我们创建,销毁复用数据库连接

    Druid的使用

    综合能Druid(德鲁伊)最好
    Druid连接池是阿里巴巴开源的数据库连接池项目

    1,下载Druid的jar包

    2,导入jar包

    3,编写代码

                            加载配置文件

                            获取数据库连接池对象

                            获取连接

    配置文件

    1. public class Myconnest {
    2. static {//静态只在类加载时加载一次
    3. try {
    4. Class.forName("com.mysql.jdbc.Driver");
    5. }catch (ClassNotFoundException e){
    6. e.printStackTrace();
    7. }
    8. }
    9. public static Connection getConnection() throws Exception {
    10. InputStream is = Myconnest.class.getResourceAsStream("druid.properties");
    11. Properties properties = new Properties();
    12. properties.load(is);
    13. DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
    14. Connection connection = dataSource.getConnection();
    15. return connection;
    16. }
    17. }

    此连接池会自动连接,会自动关闭

    试试效果

    1. public class Test {
    2. public static void main(String[] args) throws Exception {
    3. Connection connection = Myconnest.getConnection();
    4. String sql="select u_id,u_username,u_mima,u_sex,u_age from yinhang";
    5. Statement statement = connection.createStatement();
    6. ResultSet set = statement.executeQuery(sql);
    7. while (set.next()){
    8. String str1 = set.getString("u_username");
    9. System.out.println(str1);
    10. }
    11. }
    12. }

    DButils使用

    QueryRunner 方法:

    QueryRunner(DruidDataSource);//可传入DruidDataSource

     query:

            作用:执行DQL查询语句,类似与executeQuery方法

             query(连接对象,SQl,ResultSetHandler<定义的类>(),可变参数填sql?对应的值)

      update:

    作用:执行DML修改语句,类似与executeUpdate方法

     update(sql,值)

     返回值为影响行数

    1. String sql = "INSERT INTO my_user (m_user,m_password,m_name,m_sxe,m_age,m_img)VALUES(?,?,?,?,?,?)";
    2. QueryRunner queryRunner = new QueryRunner(MyconnectionUtils.getDataSource());
    3. int num = queryRunner.update(sql,user.getM_user(),user.getM_password(),user.getM_name(),user.getM_sxe(),user.getM_age(),user.getM_img());
    4. //插入语句

    ResultSetHandler:接口

    具体查询:

    BeanHandler:

                                    BeanHandler:返回一个对象

                                    注意: 1,bean类必须提供无参构造函数,如果没有无参构造会报错

                                              2,bean类的属性名要与查询的结果的列名一致,如果名称不

                                                 一致可 能会取不到值

    1. String sql = "SELECT m_id,m_user,m_password,m_name,m_age,m_money,m_img FROM my_user WHERE m_user = ? ";
    2. QueryRunner queryRunner = new QueryRunner(MyconnectionUtils.getDataSource());
    3. BeanHandler<User> userBeanHandler = new BeanHandler<>(User.class);
    4. User user = queryRunner.query(sql,userBeanHandler,username);//返回一行

    BeanListHandler:

                                    BeanListHandler:返回一个集合 注意:

                                             1,bean类必须提供无参构造函数,如果没有无参构造会报错

                                             2,bean类的属性名要与查询的结果的列名一致,如果没有无

                                                参构造 会报错 

    1. String sql="SELECT * FROM student";
    2. QueryRunner queryRunner = new QueryRunner(MyconnectionUtils.getDataSource());
    3. BeanListHandler<Student> listHandler = new BeanListHandler<>(Student.class);
    4. List<Student> query = queryRunner.query(sql, listHandler);//返回list
    5. //返回了多个

    ScalarHandler:

                                    ScalarHandler:返回一个值

  • 相关阅读:
    【原创工具】ADBGUI - GUI版ADB操作工具
    《C++Primer》-1-前序与基础第I部分重点
    netsh int ip 添加/删除 TCP 协议 excludedportrange 的方法
    最新《动手学习深度学习》配套课程视频、笔记、ppt等资源整理分享
    Linux 下使用 Docker 安装 MySQL
    win10使用WSL(Windows Subsystem for Linux)安装Ubuntu
    JS——初始DOM的相关操作练习
    SpringCloud Netflix-Zuul使用
    设计师都应该知道的事:极简主义家具该怎么去用
    QT之excel的读写
  • 原文地址:https://blog.csdn.net/weixin_44207220/article/details/127695286