• Java_Jdbc


    目录

    一.JDBC概述

    二.JDBC API

    三.ResultSet[结果集]

    四.Statement 

     五.PreparedStatement

    六. JDBC API 总结


    一.JDBC概述

    1. JDBC 为访问不同的数据库提供了同一的接口,为使用着屏蔽了细节问题
    2. Java程序员使用JDBC 可以连接任何提供了  JDBC驱动的数据库系统,从而完成对数据库的各种操作
    3. JDKC的原理图
    4. 模拟JDBC  com.hspedy.jdbc.myjdbc

    JDBC是java操作提供的一套用于数据库操作的接口API,java程序员只需要面向这套接口编程计科。不同的数据库厂商,需要针对这套接口,提供不同实现。

    二.JDBC API

    JDBC API 是一系列接口,她同一和规范了应用程序于数据的连接,执行SQL语句,并得到返回结果等各种操作,相关类和接口在java.sql与 javax.sql 包中 

     JDBC程序编写步骤

    1. 注册驱动   加载Driver类
    2. 获取连接  得到 connection
    3. 执行增删改查 发送相关的sql命令给mysql执行
    4. 释放资源    关闭相关的连接等

    1. package com.tianedu.jdbc;
    2. import com.mysql.jdbc.Driver;
    3. import java.sql.Connection;
    4. import java.sql.SQLException;
    5. import java.sql.Statement;
    6. import java.util.Properties;
    7. /**
    8. * @author tian
    9. * 这是第一个JDBC程序 完成简单的操作
    10. */
    11. public class Jdbc01 {
    12. public static void main(String[] args) throws SQLException {
    13. // 前置工作在项目下创建一个文件夹 libs
    14. // 将 mysql.jar 拷贝到该目录下,点击 add to project 加入到项目中才可以使用
    15. //1.注册驱动
    16. Driver driver = new Driver(); // 创建driver 对象
    17. //2.得到连接
    18. //(1) jdbc: // 规定好的协议,通过jdbc的方式连接mysql
    19. //(2) localhost 主机,也可以是ip地址
    20. //(3) 3306 表示MySQL 监听的端口
    21. //(4) hsp_db03 表示连接到呢个数据库
    22. // (5) MySQL的连接本质就是前面学习过sql 的连接
    23. String url = "jdbc:mysql://localhost:3306/hsp_db03";
    24. // 将用户名和密码 放到Properties 对象中
    25. Properties properties = new Properties();
    26. // 说明: user 和 password 是规定好的,后面的值根据实际情况写
    27. properties.setProperty("user","root"); // 用户
    28. properties.setProperty("password","tian"); //密码
    29. Connection connect = driver.connect(url, properties);
    30. //3.执行sql语句
    31. //String sql = "insert into actor values(null,'刘德华','男','1970-11-11',110)";
    32. // String sql = "update actor set name = '周星驰'where id = 1";
    33. String sql = "delete from actor where id = 1";
    34. // 下面的statement 用于执行静态的sql 语句并返回其生成的结果的对象
    35. Statement statement = connect.createStatement();
    36. int rows = statement.executeUpdate(sql); // 如果是dml语句,返回的就是影响行数 如果是1 添加成功 如果是0 添加失败
    37. System.out.println(rows > 0 ? "成功":"失败");
    38. //4.关闭资源
    39. statement.close();
    40. connect.close();
    41. }
    42. }

    获取数据库连接5种方式

    1. package com.tianedu.jdbc;
    2. import com.mysql.jdbc.Driver;
    3. import org.junit.Test;
    4. import java.io.FileInputStream;
    5. import java.io.IOException;
    6. import java.sql.Connection;
    7. import java.sql.DriverManager;
    8. import java.sql.SQLException;
    9. import java.util.Properties;
    10. /**
    11. * @author tian
    12. * 分析java 连接MySQL的物种方式
    13. */
    14. public class JdbcConn {
    15. @Test
    16. public void connect01() throws SQLException {
    17. Driver driver = new Driver();
    18. String url = "jdbc:mysql://localhost:3306/hsp_db03";
    19. // 将用户名和密码放入到Properties 对象
    20. Properties properties = new Properties();
    21. properties.setProperty("user", "root");
    22. properties.setProperty("password", "tian");
    23. Connection connect = driver.connect(url, properties);
    24. System.out.println(connect);
    25. }
    26. //方式2
    27. @Test
    28. public void connect02() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
    29. //使用反射加载Driver 动态加载,更加灵活,减少依赖性
    30. Class aClass = Class.forName("com.mysql.jdbc.Driver");
    31. Driver driver = (Driver)aClass.newInstance();
    32. String url = "jdbc:mysql://localhost:3306/hsp_db03";
    33. // 将用户名和密码放入到Properties 对象
    34. Properties properties = new Properties();
    35. properties.setProperty("user", "root");
    36. properties.setProperty("password", "tian");
    37. Connection connect = driver.connect(url, properties);
    38. System.out.println("方式2=" + connect);
    39. }
    40. // 方式3 使用DriverManager 替代 Driver 进行统一管理
    41. @Test
    42. public void connect03() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
    43. // 使用反射 加载Driver
    44. Class aClass = Class.forName("com.mysql.jdbc.Driver");
    45. Driver driver = (Driver) aClass.newInstance();
    46. //创建 url 和 user 和 password
    47. String url = "jdbc:mysql://localhost:3306/hsp_db03";
    48. String user = "root";
    49. String password = "tian";
    50. DriverManager.registerDriver(driver); //注册Driver 驱动
    51. Connection connection = DriverManager.getConnection(url, user, password);
    52. System.out.println("第三种方式" + connection);
    53. }
    54. // 方式4 使用Class.forName 自动完成注册,简化代码
    55. // 使用最多
    56. @Test
    57. public void connect04() throws ClassNotFoundException, SQLException {
    58. // 使用反射加载 Driver 类
    59. // 在加载Driver类时,完成注册
    60. /*
    61. 源码: 1.静态代码块,在类加载时,会执行一次
    62. 2.DriverManager.registerDriver(new Driver());
    63. 3.因此 加载和注册Driver 的工作已经完成
    64. static {
    65. try {
    66. DriverManager.registerDriver(new Driver());
    67. } catch (SQLException var1) {
    68. throw new RuntimeException("Can't register driver!");
    69. }
    70. }
    71. */
    72. Class.forName("com.mysql.jdbc.Driver") ; //如果没有这句也可以执行,建议写上更加明确
    73. // MySQL 驱动 5.1.6 可以无需Class.forName("com.mysql.jdbc.Driver");
    74. // 从 jdk1.5 以后使用Jdbc4 不在需要显示调用class.forName() 注册驱动而已自动调用驱动
    75. // jar包下META-INF\services\java.sql.Driver文本种的类 名称去注册
    76. String url = "jdbc:mysql://localhost:3306/hsp_db03";
    77. String user = "root";
    78. String password = "tian";
    79. Connection connection = DriverManager.getConnection(url,user,password);
    80. System.out.println("第四种方式" + connection);
    81. }
    82. @Test
    83. // 方式5,在方式4的基础上改进,增加配置文件,让信息连接MySQL更加灵活
    84. public void connect05() throws IOException, ClassNotFoundException, SQLException {
    85. //通过Properties 对象获取配置文件的信息
    86. Properties properties = new Properties();
    87. properties.load(new FileInputStream("src\\mysql.properties"));
    88. // 获取相关的值
    89. String user = properties.getProperty("user");
    90. String password = properties.getProperty("password");
    91. String driver = properties.getProperty("driver");
    92. String url = properties.getProperty("url");
    93. Class.forName(driver); //建议写上 更加明确
    94. Connection connection = DriverManager.getConnection(url, user, password);
    95. System.out.println("方式5" + connection);
    96. }
    97. }

    三.ResultSet[结果集]

    1. 表示数据库结果的数据表,通常通过执行查询数据库的语言生成
    2. ResultSet对象保持一个光标指向其当中的数据行,最初,给光标位于第一行之间
    3. next方法将光标移动到下一行,并且由于在ResultSet对象种没有更多行时返回false,因此可以在while 循环中使用循环来遍历结果集
    1. package com.tianedu.jdbc.resultest_;
    2. import java.io.FileInputStream;
    3. import java.io.IOException;
    4. import java.sql.*;
    5. import java.util.Properties;
    6. /**
    7. * @author tian
    8. *
    9. * 演示select 语句返回一个resultset 并取出结果
    10. */
    11. @SuppressWarnings({"all"})
    12. public class ResultSet_ {
    13. public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
    14. //通过Properties 对象获取配置文件
    15. Properties properties = new Properties();
    16. properties.load(new FileInputStream("src\\mysql.properties"));
    17. // 获取相关的值
    18. String user = properties.getProperty("user");
    19. String password = properties.getProperty("password");
    20. String driver = properties.getProperty("driver");
    21. String url = properties.getProperty("url");
    22. Class.forName(driver); //建议写上 更加明确
    23. Connection connection = DriverManager.getConnection(url, user, password);
    24. //得到Statement
    25. Statement statement = connection.createStatement();
    26. //组织sql 语句
    27. String sql = "select id,name,sex,borndate from actor";
    28. //执行给定的sql语句,该语句返回单个 ResultSet对象
    29. ResultSet resultSet = statement.executeQuery(sql);
    30. // 使用where 循环取出数据
    31. while (resultSet.next()) {
    32. // 让光标向后移动 如果没有更多的记录则返回false
    33. int id = resultSet.getInt(1);
    34. String name = resultSet.getString(2);// 获取该行第二列
    35. String sex = resultSet.getString(3);
    36. Date date = resultSet.getDate(4);
    37. System.out.println(id + "\t" + name + "\t" + sex + "\t" + date);
    38. // 获取该行的对第一列
    39. }
    40. // 关闭连接
    41. resultSet.close();
    42. connection.close();
    43. statement.close();
    44. }
    45. }

    四.Statement 

    1. statement 对象 用于执行静态SQL语句返回生成的结果的对象
    2. 在连接建立后,需要对数据库进行访问,执行命令或是sql 语句,可以通过 Statement【存在sql注入】,PerparedStatement【预处理】,CallableStatement【存储过程】
    3. Statement对象执行sql语句,存在sql 注入风险
    4. sql 注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的sql 语句或命令,恶意攻击数据库。sql_injection.sql
    5. 要防范sql注入,只要用PerparedStatement(从Statement 扩展而来)取代Statement 就可以了
    1. package com.tianedu.jdbc.statement_;
    2. import java.io.FileInputStream;
    3. import java.sql.Connection;
    4. import java.sql.DriverManager;
    5. import java.sql.ResultSet;
    6. import java.sql.Statement;
    7. import java.util.Properties;
    8. import java.util.Scanner;
    9. /**
    10. * @author tian
    11. * 演示statement 的注入问题
    12. */
    13. @SuppressWarnings({"all"})
    14. public class Statement_ {
    15. public static void main(String[] args) throws Exception {
    16. Scanner scanner = new Scanner(System.in);
    17. //让用户输入管理员姓名和密码
    18. System.out.print("请输入管理员的名字:");
    19. String admin_name = scanner.nextLine(); //next当接受到空格或者 ' 表示结束
    20. System.out.print("请输入管理员的密码:");
    21. String admin_pwd = scanner.nextLine();
    22. // 通过Properties 对象获取配置文件的信息
    23. Properties properties = new Properties();
    24. properties.load(new FileInputStream("src\\mysql.properties"));
    25. // 获取相关的值
    26. String user = properties.getProperty("user");
    27. String password = properties.getProperty("password");
    28. String driver = properties.getProperty("driver");
    29. String url = properties.getProperty("url");
    30. //1.注册驱动
    31. Class.forName(driver);
    32. //2.得到连接
    33. Connection connection = DriverManager.getConnection(url,user,password);
    34. //3.得到Statement
    35. Statement statement = connection.createStatement();
    36. //4.组织sql
    37. String sql = "select name,pwd from admin where name = '"
    38. +admin_name+"' and pwd= '"+admin_pwd+"'" ;
    39. ResultSet resultSet = statement.executeQuery(sql);
    40. if(resultSet.next()){
    41. //如果查询到一条记录,则说明该管理员存在
    42. System.out.println("登录成功");
    43. } else {
    44. System.out.println("对不起,登录失败");
    45. }
    46. // 关闭连接
    47. resultSet.close();
    48. statement.close();
    49. connection.close();
    50. }
    51. }

     五.PreparedStatement

    1. PreparedStatement 执行的sql语句中的参数用问号(?)来表示,调用PerparedStatement 对象的setXxxx() 方法来设置这些参数。setXxx() 方法有两个参数,第一个参数是要设置的sql语句中的索引(从1开始),第二个是设置的sql 语句中的参数值
    2. 调用 executeQuery() 返回ResultSet 对象
    3. 调用 executeUpdate(): 执行更新,包括增,删,修改

     预处理好处

    1. 不在使用 + 拼接sql语句,减少语法错误
    2. 有效的解决了sql注入问题
    3. 大大减少了编译次数,效率较高
    1. package com.tianedu.jdbc.preparedstatement_;
    2. import java.io.FileInputStream;
    3. import java.sql.Connection;
    4. import java.sql.DriverManager;
    5. import java.sql.PreparedStatement;
    6. import java.util.Properties;
    7. import java.util.Scanner;
    8. /**
    9. * @author tian
    10. *
    11. * 演示 preparedStatement使用
    12. */
    13. @SuppressWarnings({"all"})
    14. public class PreparedStatementDML_ {
    15. public static void main(String[] args) throws Exception {
    16. Scanner scanner = new Scanner(System.in);
    17. //让用户输入管理员姓名和密码
    18. System.out.print("请输入添加的名字:");
    19. String admin_name = scanner.nextLine(); //next当接受到空格或者 ' 表示结束
    20. // System.out.print("请输入管理员的密码:");
    21. //String admin_pwd = scanner.nextLine();
    22. //通过Properties
    23. Properties properties = new Properties();
    24. properties.load(new FileInputStream("src\\mysql.properties"));
    25. //获取相关的值
    26. String user = properties.getProperty("user");
    27. String password = properties.getProperty("password");
    28. String driver = properties.getProperty("driver");
    29. String url = properties.getProperty("url");
    30. // 注册驱动
    31. Class.forName(driver);
    32. //得到连接
    33. Connection connection = DriverManager.getConnection(url,user,password);
    34. // 组织sql sql语句的 ? 相当于占位符
    35. // 添加一个记录
    36. //String sql = "insert into admin values(?,?)";
    37. //String sql = "update admin set pwd = ? where name = ?";
    38. String sql = "delete from admin where name = ?";
    39. //3.2 preparedStatement 对象实现了 preparedStatement 接口的实现类的对象
    40. PreparedStatement preparedStatement = connection.prepareStatement(sql);
    41. //3.3 给?赋值
    42. preparedStatement.setString(1,admin_name);
    43. //preparedStatement.setString(1,admin_pwd);
    44. //4.执行DML 语句使用 executeUpdate
    45. int rows = preparedStatement.executeUpdate();
    46. System.out.println(rows > 0 ? "执行成功":"执行失败");
    47. //关闭连接
    48. preparedStatement.close();
    49. connection.close();
    50. }
    51. }

    六. JDBC API 总结

    • Driver Manager 驱动管理类  getConnection(url,user,pwd) 获取连接
    • Connection 接口  creatStatement 创建Statement 对象(使用较少,存在注入问题)                 preparedStatement(sql) 生成一个预处理对象
    • Statement 接口   executeUpdate(sql) 执行dml语句 返回影响得到行数                                       executeQuery(sql) 执行查询,返回ResultSet对象                                                                      execute(sql) 执行任意的sql 返回的是布尔值
      • PreparedStatement 接口  excuteUpdate() 执行Dml语句                                                    excuteQuery() 执行查询   返回ResultSet                                                                    excute() 执行任意的sql 返回一个布尔值                                                                              setXxx(站位符索引,占位符的值) 可以解决sql 注入                                                        setObject(站位符的索引,站位符的值)                                                                                  ResultSet(结果集)  next() 方法向下移动一行     同时如果没有下一行,返回false              previous() 向上移动一行                                                                                                      getXX(列的索引 | 列名)         返回对应类的值 接受类型是Xxx                                            getObject(列的索引 | 列名)  返回对应列的值,接受类型为object                                       
  • 相关阅读:
    接口自动化测试框架:Pytest+Allure+Excel
    关于印发《深圳市福田区支持战略性新兴产业和未来产业集群发展若干措施》的通知
    mybatis缓存介绍
    深入理解 Python 描述符
    记一次用jlink调试正常,不进入调试就不能运行的情况
    2022年06月 C/C++(七级)真题解析#中国电子学会#全国青少年软件编程等级考试
    MySQL数据库
    格林公式的理解
    C++ 共享内存相关的API
    技术应用:利用Lua脚本提升Redis操作效率与功能
  • 原文地址:https://blog.csdn.net/weixin_68773927/article/details/133853283