• JDBC:使用PreparedStatement操作数据表


    使用PreparedStatement 操作数据表,完成增删改查操作。

     一、基本增删改-操作:示例

    1.通过JdbcUtils中的连接方法获取连接

    conn = JdbcUtils.getConnection();

    2.预编译sql语句,返回PreparedStatement的实例

    1. String sql = "insert into customers(name,email)values(?,?)";// ? 是占位符
    2. ps = conn.prepareStatement(sql);

    3.填充占位符:输入需要添加/修改/删除的值

    1. ps.setString(1, "peter-pan");
    2. ps.setString(2, "peter@look.com");

    4.执行操作

    ps.execute();

    5.关闭资源

    1. try {
    2. if (ps != null)
    3. ps.close();
    4. } catch (SQLException e) {
    5. e.printStackTrace();
    6. }
    7. try {
    8. if (conn != null)
    9. conn.close();
    10. } catch (SQLException e) {
    11. e.printStackTrace();
    12. }

    图示:

     

     二、通用的增删改操作

    1.准备通用方法,加入形参:sql语句和可变形参的占位符;注:sql中占位符的个数与可变形参的长度相同

    public void update(String sql,Object...args){}

    2.在方法内部:

            2.1.获取连接,返回PreparedStatement实例

    1. Connection conn = null;
    2. PreparedStatement ps = null;
    3. conn = JdbcUtils.getConnection();
    4. ps = conn.prepareStatement(sql);

            2.2使用for循环填充占位符

    1. for (int i = 0; i < args.length; i++) {
    2. ps.setObject(i+1,args[i]);
    3. }

    3.执行操作

    4.关闭资源

    方法体代码示例:

    1. public void update(String sql,Object...args){//sql中占位符的个数与可变形参的长度相同
    2. Connection conn = null;
    3. PreparedStatement ps = null;
    4. try {
    5. conn = JdbcUtils.getConnection();
    6. ps = conn.prepareStatement(sql);
    7. for (int i = 0; i < args.length; i++) {
    8. ps.setObject(i+1,args[i]);
    9. }
    10. ps.execute();
    11. } catch (Exception e) {
    12. e.printStackTrace();
    13. } finally {
    14. JdbcUtils.closeResource(conn,ps);
    15. }

    操作代码示例:

    1. public void test3(){
    2. String sql = "update `order` set order_name = ? where order_id = ?";
    3. update(sql, "DD", "2");
    4. String sql1 ="update `order` set order_name =? where order_id=?";
    5. update(sql1,"CG","1");
    6. }

    三、基本查询操作

    1.获取数据库连接,返回PreparedStatement实例

    2.调用setObject()方法给占位符赋值

    3.执行并返回结果集

    rs = ps.executeQuery();

     4.处理结果集、并关闭资源

    1. if (rs.next()) {//next():判断结果集的下一条是否有数据,如果有数据返回true,并指针下移,如果返回false,指针不会下移
    2. //获取当前这条数据的各个字段值
    3. int id = rs.getInt(1);
    4. String name = rs.getString(2);
    5. String email = rs.getString(3);
    6. Date birth = rs.getDate(4);
    7. //将数据封装为一个对象
    8. Customer customer = new Customer(id, name, email, birth);
    9. System.out.println(customer);
    10. }

    图示:

    四、通用的查询操作 :不同表查询均可使用

    1.编写Query()方法:传入形参:泛型,sql语句及可变形参()

        public  List getForList(Class clazz, String sql, Object... args) {
    

    2.获取数据库连接、返回PreparedStatement实例

    3.使用for循环获取占位符并设置 

     4.执行

    5.获取结果集的元数据

    ResultSetMetaData rsmd = rs.getMetaData();

     6.通过rsmd获取结果集的列数

    int columnCount = rsmd.getColumnCount();

    7.处理结果集

    1. if (rs.next()) {
    2. //创建一个泛型对象实例
    3. T t = clazz.newInstance();
    4. //处理结果集一行数据中的每一列
    5. for (int i = 0; i < columnCount; i++) {
    6. //获取数据
    7. Object columValue = rs.getObject(i + 1);
    8. //获取每个列的列名
    9. String columnLabel = rsmd.getColumnLabel(i + 1);
    10. //给t对象指定columName的属性,赋值为columValue:通过反射
    11. Field field = clazz.getDeclaredField(columnLabel);
    12. //field.setAccessible(true) 设置可以访问private变量的变量值
    13. field.setAccessible(true);
    14. //给对象的Filed属性设置value
    15. field.set(t, columValue);
    16. }
    17. //返回结果
    18. return t;
    19. }

    8.关闭资源

    方法体代码:

    1. public T getInstance(Class clazz, String sql, Object... args) {
    2. Connection conn = null;
    3. PreparedStatement ps = null;
    4. ResultSet rs = null;
    5. try {
    6. conn = JdbcUtils.getConnection();
    7. ps = conn.prepareStatement(sql);
    8. for (int i = 0; i < args.length; i++) {
    9. ps.setObject(i + 1, args[i]);
    10. }
    11. rs = ps.executeQuery();
    12. //获取结果集的元数据:ResultSetMetaData
    13. ResultSetMetaData rsmd = rs.getMetaData();
    14. //通过rsmd获取结果集中的列数
    15. int columnCount = rsmd.getColumnCount();
    16. if (rs.next()) {
    17. //创建一个泛型对象实例
    18. T t = clazz.newInstance();
    19. //处理结果集一行数据中的每一列
    20. for (int i = 0; i < columnCount; i++) {
    21. //获取数据
    22. Object columValue = rs.getObject(i + 1);
    23. //获取每个列的列名
    24. String columnLabel = rsmd.getColumnLabel(i + 1);
    25. //给t对象指定columName的属性,赋值为columValue:通过反射
    26. Field field = clazz.getDeclaredField(columnLabel);
    27. //field.setAccessible(true) 设置可以访问private变量的变量值
    28. field.setAccessible(true);
    29. field.set(t, columValue);
    30. }
    31. return t;
    32. }
    33. } catch (Exception e) {
    34. e.printStackTrace();
    35. } finally {
    36. JdbcUtils.closeResource(conn,ps,rs);
    37. }
    38. return null;
    39. }

    测试代码:

    1. @Test
    2. public void test(){
    3. /* String sql = "select id,name,email from customers where id =?";
    4. Customer customer = getInstance(Customer.class,sql,12);
    5. System.out.println(customer);*/
    6. String sql1 = "select order_id orderId,order_name orderName from `order` where order_id = ?";
    7. Order order = getInstance(Order.class,sql1,1);
    8. System.out.println(order);
    9. String sql2 = "select id,name,email,birth from `customers` where id = ?";
    10. Customer cust = getInstance(Customer.class, sql2, 2);
    11. System.out.println(cust);
    12. }

    【注意】:针对于表的字段名与类的属性名不相同的情况:

    1.必须在声明sql时,使用类的属性名来命名字段的别名

    2.使用ResultSetMetaData时,需要使用getColumnLabel()来替换getColumnName(),获取列的别名。

    说明:如果sql中没有给字段起别名,getColumnLabel()获取的就是列名

  • 相关阅读:
    Java String类(3):StringBulider和StringBuffer详解
    仓颉编程语言入门
    BATJ最全架构技术合集:Docker+Spring+Nginx+Netty+MySQL
    自定义appbarTitle + TabBarView 实现类似安卓tabHost+Fragment
    Dubbo的注解配置和XML配置
    前端缓存机制——强缓存、弱缓存、启发式缓存
    YOLO系列目标检测算法——PP-YOLO
    JDK1.8的安装与配置
    Word控件Spire.Doc 【段落处理】教程(十六):C#中如何设置段落前后的间距
    VR全景航拍要注意什么,航拍图片如何处理
  • 原文地址:https://blog.csdn.net/m0_57753335/article/details/126319621