zoukankan      html  css  js  c++  java
  • JDBC:Statement问题

    1、Statement问题

     2、解决办法:通过PreparedStatement代替

     实践:

    package com.dgd.test;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.sql.*;import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) throws SQLException, ClassNotFoundException, FileNotFoundException {
    
            Scanner sc = new Scanner(System.in);
            System.out.print("输入序号:");
            int id=sc.nextInt();
            System.out.print("输入名称:");
            String name=sc.next();
    
    
            // System.out.println("1111");
            Class.forName("com.mysql.cj.jdbc.Driver");
    
            String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT";
            Connection conn = DriverManager.getConnection(url, "root", "123456");
            System.out.println(conn.getClass());
    
            String sql="INSERT INTO stu VALUES(?,?,?)";
            PreparedStatement s = conn.prepareStatement(sql);
            s.setObject(1,id);
            s.setObject(2,name);
            FileInputStream fis=new FileInputStream("C:/Users/Zhang/Pictures/IMG_20190930_053816.jpg");
            s.setObject(3,fis);
    
            int len=s.executeUpdate();
            System.out.println(len>0?"插入成功":"插入失败");
    
    
            s.close();
            conn.close();
            sc.close();
    
    /*
            String sql="INSERT INTO stu VALUES(2,'zhangkun')";
            String sql2="SELECT * FROM stu";
            Statement s=conn.createStatement();
            int len=s.executeUpdate(sql);
            System.out.println(len>0?"添加成功":"添加失败");
    
            ResultSet set=s.executeQuery(sql2);
            while(set.next())
            {
                System.out.print("学号:"+set.getInt(1)+"	"+"姓名:"+set.getString(2)+"
    ");
            }
            set.close();;
            s.close();
            conn.close();
     */
    
         }
    }

    总结JDBC的步骤:

    1  获取连接      注册驱动,DriverManager ,url , username, password

    2  编写SQL      String sql="    ?"

    3  预编译SQL    PreparedStatement

    4  设置参数       .setObject

    5  执行SQL       .executeQuery   or   executeUpdate   

    6  封装结果        ResultSet

    7  关闭连接        .close()

  • 相关阅读:
    java 整合redis缓存 SSM 后台框架 rest接口 shiro druid maven bootstrap html5
    《将博客搬至CSDN》
    前后端分离-定义响应格式化数据
    微服务-Springboot+Redis缓存管理接口代码实现
    java语法
    java后台树形结构展示---懒加载
    后端处理前端传过来的日期的两种方式
    汉字转拼音工具类
    Mybatis的小技巧
    调用高德API,通过输入的地址,如省份、市、区获取经纬度 ,通过输入的经纬度,获取区域详情
  • 原文地址:https://www.cnblogs.com/lemonzhang/p/12794563.html
Copyright © 2011-2022 走看看