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()

  • 相关阅读:
    BZOJ 3218: a + b Problem
    P4542 [ZJOI2011]营救皮卡丘
    P4843 清理雪道
    P4553 80人环游世界
    P4126 [AHOI2009]最小割
    P2619 [国家集训队2]Tree I
    P2469 [SDOI2010]星际竞速
    P2050 [NOI2012]美食节
    易语言入门
    jdbc连接oracle语法
  • 原文地址:https://www.cnblogs.com/lemonzhang/p/12794563.html
Copyright © 2011-2022 走看看