zoukankan      html  css  js  c++  java
  • JDBC:获取自增长键值的序号

    1、改变的地方

     实践:

    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(null ,?,?)";
            PreparedStatement s = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            s.setObject(1,name);
            FileInputStream fis=new FileInputStream("C:/Users/Kun Zhang/Pictures/IMG_20190930_053816.jpg");
            s.setObject(2,fis);
    
            int len=s.executeUpdate();
            System.out.println(len>0?"插入成功":"插入失败");
            ResultSet res=s.getGeneratedKeys();//mysql服务器通过结果集getGeneratedKeys将增长的键值返回
            if(res.next())
            {
                id=res.getInt(1);
                System.out.println("添加的序号为"+id );
            }
    
    
    
            s.close();
            res.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();
     */
    
         }
    }

  • 相关阅读:
    SoapUI 使用笔记
    git 使用笔记(二)
    git 使用笔记(一)
    jquery 拓展
    hdu 1024 Max Sum Plus Plus (DP)
    hdu 2602 Bone Collector (01背包)
    hdu 1688 Sightseeing (最短路径)
    hdu 3191 How Many Paths Are There (次短路径数)
    hdu 2722 Here We Go(relians) Again (最短路径)
    hdu 1596 find the safest road (最短路径)
  • 原文地址:https://www.cnblogs.com/lemonzhang/p/12795219.html
Copyright © 2011-2022 走看看