• JDBC获得数据库表中的auto_increment类主键


        在对表进行插入数据时,如果主键是自增长类型,那么我们可以不对主键那一列进行赋值,但是有时候,这个主键恰好是别的表的外键,那么我们需要知道这次自增长的值,当然我们可以执行一次查询语句,根据你插入的信息当条件,简便方法就是在执行插入sql语句后,可以直接返回该主键。

    package jdbc_preparement;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.sql.Blob;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class text_preparestartment {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
          Connection con=simplecon.getConnection();  //创建JDBC连接,用封装好的自定义类
          String sql="insert into t_user values(null,?,?,null);";try {
            PreparedStatement ps=con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); //多一个参数,表示需要返回主键
            ps.setString(1, "mike");
            ps.setString(2, "4399");
            ps.execute();
            ResultSet re=ps.getGeneratedKeys();    //返回主键
            re.next();
            int n=re.getInt(1);
            System.out.println("自然增长的序号为"+n);  //输出主键
            simplecon.close(re);
            simplecon.close(ps);
            simplecon.close(con);
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        }
    
    }
    class simplecon
    {
        static Connection con;
        static Connection getConnection()
        {   
            try{
                con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","数据库用户名","数据库密码");    
            }catch(SQLException e){
                e.printStackTrace();
            }
            return con;
        }
        static void close(AutoCloseable a)
        {
            try {
                a.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    后端架构师技术图谱
    互联网经典技术架构
    软件开发知识体系(二)
    软件开发知识体系(一)
    HSF源码剖析
    分库分表的几种常见形式以及可能遇到的难题
    iOS 关于MVC和MVVM设计模式的那些事
    MVC与MVP简单对比
    MVC、MVP、MVVM 模式
    Learning Android ActionBar
  • 原文地址:https://www.cnblogs.com/llsq/p/7744673.html
Copyright © 2020-2023  润新知