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)+"\t"+"姓名:"+set.getString(2)+"\n"); } set.close();; s.close(); conn.close(); */ } }