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

  • 相关阅读:
    MongoDB在windows服务器安装部署及远程连接MongoDB
    react 常用组件
    react component 语法报错解决
    yarn install node-sass(gulp-sass) 安装失败解决方案
    eslint 规则中文注释
    react jsx 代码格式化
    vue sublime 工欲善其事,必先利其器
    jenkins 配置
    nodejs 使用 superagent 与 cheerio 完成简单爬虫
    jQuery DOM对象区别与联系
  • 原文地址:https://www.cnblogs.com/lemonzhang/p/12795219.html
Copyright © 2011-2022 走看看