JDBC插入表中一个数据返回其自增主键

Connection connection = JDBCUtils.getConnection();   //获取一个链接
String sql ="insert into book values (null ,?)";   //数据库book表中只有一个id自增跟书名字段
PreparedStatement preparedStatement = connection.prepareStatement(sql , Statement.RETURN_GENERATED_KEYS);//后面加个参数,说明这个preparedStatement是个有返回值的变量
preparedStatement.setString(1 ,"C++");
preparedStatement.executeUpdate();//执行成功
ResultSet generatedKeys = preparedStatement.getGeneratedKeys();  //取返回的自增主键的id
while(generatedKeys.next()){   //因为返回的是一个resultset结果集 所以需要遍历
    int id = generatedKeys.getInt(1);   //此刻getInt(1)固定写法 因为只返回一个值,只能写1
    System.out.println("返回插入之后的数据的自增id为:"+id);
}

下篇介绍JDBC批量插入数据 链接为https://mp.csdn.net/postedit/82430209

----------------------------------------------------------------------------------------------------------

JDBCUtilsjava工具类

public class JDBCUtils {
    //static  Properties properties;
    private static String url;
    private static String driver;
    private static String username;
    private static String password;
    static{
        Properties properties = new Properties();
        try {
            //properties.load(new FileInputStream(new File("db.properties")));
            properties.load(JDBCUtils.class.getResourceAsStream("/db.properties"));//读取文件变成流

            //读取数据
            url = properties.getProperty("url");
            driver = properties.getProperty("driverClass");
            username = properties.getProperty("user");
            password = properties.getProperty("password");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 获取连接
    public static Connection getConnection(){
     /*   String url ="jdbc:mysql://localhost:3306/day04";
        String username="root";
        String password = "123456";*/
        Connection connect =null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connect = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connect;
    }
    //关闭
    public static void closeAll(Connection con , Statement statm , ResultSet result){

            try {
                if(result !=null){
                    result.close();
                }
                if(statm !=null){
                    statm.close();
                }
                if(con !=null){
                con.close();
                }

            } catch (SQLException e) {
                e.printStackTrace();
            }

    }
}

猜你喜欢

转载自blog.csdn.net/qq_32736999/article/details/82430125