Java Web基础入门第五十三讲 获得MySQL数据库自动生成的主键
发布日期:2021-06-30 17:58:17 浏览次数:2 分类:技术文章

本文共 1517 字,大约阅读时间需要 5 分钟。

有时候在开发中要获得MySQL数据库自动生成的主键,那么该如何获得呢?我们可以查看JDK API 1.6.0文档,就能知道Connection接口里面有一个如下方法:

在这里插入图片描述
注释:autoGeneratedKeys指示是否应该返回自动生成的键的标志,它是 Statement.RETURN_GENERATED_KEYS或Statement.NO_GENERATED_KEYS之一。
首先,编写测试的SQL语句。

create table test (    id int primary key auto_increment,    name varchar(40));

然后,编写测试代码,如下所示:

package cn.liayun.demo;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import cn.liayun.utils.JdbcUtils;public class Demo4 {
/* create table test ( id int primary key auto_increment, name varchar(40) ); */ //获取自动生成的主键 public static void main(String[] args) throws SQLException {
Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try {
conn = JdbcUtils.getConnection(); String sql = "insert into test(name) values('liyunling')"; /* * PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) * autoGeneratedKeys - 指示是否应该返回自动生成的键的标志,它是 Statement.RETURN_GENERATED_KEYS或Statement.NO_GENERATED_KEYS之一 * * st = conn.prepareStatement(sql)默认是不返回自动生成的主键的 */ st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);// Statement.RETURN_GENERATED_KEYS参数:是否得到sql语句生产的主键 st.executeUpdate(); rs = st.getGeneratedKeys(); if (rs.next()) {
System.out.println(rs.getInt(1)); } } finally {
JdbcUtils.release(conn, st, rs); } }}

注意:st = conn.prepareStatement(sql);默认是不返回自动生成的主键的。

转载地址:https://liayun.blog.csdn.net/article/details/52304439 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Java Web基础入门第五十四讲 使用JDBC调用存储过程
下一篇:Java Web基础入门第五十二讲 使用JDBC进行批处理

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年05月01日 01时03分04秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

【深度学习笔记】用torch.nn.Sequential()搭建神经网络模型 2019-04-30
【深度学习笔记】用torch.nn.ModuleList搭建神经网络 2019-04-30
【解决错误】AttributeError: module ‘scipy.misc‘ has no attribute ‘imread‘ 2019-04-30
【解决错误】复现RCAN的时候遇到了ImportError: cannot import name ‘_update_worker_pids’ from ‘torch._C’ 2019-04-30
【解决错误】ModuleNotFoundError: No module named ‘skimage‘ 2019-04-30
【深度学习笔记】pytorch的点乘(dot product) 2019-04-30
【深度学习笔记】残差 2019-04-30
【错误解决】cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\sr 2019-04-30
【python学习笔记】读取指定文件夹中的图片,结合边缘保留滤波EPF 2019-04-30
【工具和环境】Linux下安装pycharm 2019-04-30
【Accumulation】The last two sentences of the abstract 2019-04-30
【Accumulation】The definition of SISR 2019-04-30
【工具与环境】Windows下安装Sublime Text 3 2019-04-30
【解决错误】ValueError: some of the strides of a given numpy array are negative. 2019-04-30
【工具与环境】Excel中批量插入行 2019-04-30
【个人实验注意事项】 2019-04-30
【解决错误】ModuleNotFoundError: No module named ‘tqdm‘ 2019-04-30
【解决错误】ModuleNotFoundError: No module named ‘PIL‘ 2019-04-30
【学习笔记】对vanilla的一些个人理解 2019-04-30
【解决错误】json.decoder.JSONDecodeError: Expecting value: line 11 column 14 (char 82) 2019-04-30