• 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();
     */
    
         }
    }

  • 相关阅读:
    【整理】Dword、LPSTR、LPWSTR、LPCSTR、LPCWSTR、LPTSTR、LPCTSTR
    C/C++中printf和C++中cout的输出格式
    左值的理解(给渴望学习的新手)
    c++ 指针精髓
    c++中的函数前面加个LRESULT是什么意思啊?
    pb调用vc写的动态链接库文件
    C++问题 & *用法
    vs2008下MFC内存泄露问题一点经验
    mysql5.6.41winx64安装
    开发是一件需要非常小心的工作
  • 原文地址:https://www.cnblogs.com/lemonzhang/p/12795219.html
Copyright © 2020-2023  润新知