在对表进行插入数据时,如果主键是自增长类型,那么我们可以不对主键那一列进行赋值,但是有时候,这个主键恰好是别的表的外键,那么我们需要知道这次自增长的值,当然我们可以执行一次查询语句,根据你插入的信息当条件,简便方法就是在执行插入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();
        }
    }
}
 posted on 2017-10-27 18:14  几缕清风依旧  阅读(353)  评论(0)    收藏  举报