如何取得刚插入数据库的数据的id m…

本文介绍了在多线程环境下获取数据库表中最新插入记录ID的三种方法:使用getGeneratedKeys()方法、LAST_INSERT_ID函数及select @@IDENTITY语句,并讨论了各自的适用场景。

(原)

两条SQl语句

第一步 insert 语句

第二步 根据插入字段查询出id

即 select id from tab where (关键条件,确保几个条件的组合是唯一的)

(转)

转自于:http://hi.baidu.com/hlz_1987/blog/item/99b27faff0b82ce6faed50e0.html,仅供学习

插入后用 
SELECT   LAST_INSERT_ID(); 
获得刚插入的id号,多客户端并发插入对取到的id号不会有问题,因为各线程独立。

 

,我也查到一种方法: 
select   @@session.identity;

 

 

我们在写数据库程序的时候,经常会需要获取某个表中的最大序号数,

一般情况下获取刚插入的数据的id,使用select max(id) from table 是可以的。
但在多线程情况下,就不行了。

下面介绍三种方法

(1) getGeneratedKeys()方法:

程序片断:

Connection conn = ;
        Serializable ret = null;
        PreparedStatement state = .;
        ResultSet rs=null;
        try {
            state.executeUpdate();
            rs = state.getGeneratedKeys();
            if (rs.next()) {
                ret = (Serializable) rs.getObject(1);
                 
        } catch (SQLException e) {
       
        return ret;

(2)LAST_INSERT_ID:

LAST_INSERT_ID 是与table无关的,如果向表a插入数据后,再向表b插入数据,LAST_INSERT_ID会改变。

在多用户交替插入数据的情况下max(id)显然不能用。
这就该使用LAST_INSERT_ID了,因为 LAST_INSERT_ID是基于Connection的,只要每个线程都使用独立的Connection对象,LAST_INSERT_ID函数将返 回该Connection对AUTO_INCREMENT列最新的insert or update*作生成的第一个record的ID。这个值不能被其它客户端(Connection)影响,保证了你能够找回自己的 ID 而不用担心其它客户端的活动,而且不需要加锁。使用单INSERT语句插入多条记录,  LAST_INSERT_ID返回一个列表。

(3)select @@IDENTITY:

String sql="select @@IDENTITY";

@@identity是表示的是最近一次向具有identity属性(即自增列)的表插入数据时对应的自增列的值,是系统定义的 全局变量。一般系统定义的全局变量都是以@@开头,用户自定义变量以@开头。比如有个表A,它的自增列是id,当向A表插入一行数据后,如果插入数据后自 增列的值自动增加至101,则通过select @@identity得到的值就是101。使用@@identity的前提是在进行insert操作后,执行select @@identity的时候连接没有关闭,否则得到的将是NULL值。

 

 

 

注:在java中使用last_insert_id();是要在一插入后就使用,也就是不能新建立Connection

比如insert建了一个 Connection,用last_insert_id()就要用同一个Connection,不能在两条查询语句(即“insert into。。。”和"select last_insert_id()")都使用getConn()创建新管道,正确的做法是insert语句getConn()创建了管道以 后,"select last_insert_id()"就直接用全局变量的conn也就是创建好的同一管道查询才有效果,否则会返回0得不到新插入的自动增长列列号,切 忌!!!!!!!!!

<table align="center" border="0" cellpadding="0" cellspacing="0" class="tableForm" style="table-layout: fixed;"> <colgroup> <col width="80" /> <col /><!--hide4phone.start--> <col width="80" /> <col width="380" /><!--hide4phone.end--> </colgroup> <tbody> <tr> <td style="text-align: right;"> <span style="color: rgb(255, 0, 0);">*</span>Subject:</td> <td dbf.type="required" id="dbf.subject"> </td> <!--show4phone.start></tr><tr><show4phone.end--> <td style="text-align: right;"> Status:</td> <td><span id="mapping.dbf.procXSource"> </span>      Responsor: <span id="mapping.dbf.responsorSource"> </span>      Participants: <span id="mapping.dbf.participantsSource"> </span></td> </tr> </tbody> </table> <div> </div> <div style="text-align: center;"> <h1><img src="../common/logo.png" /> [Form Name]</h1> </div> <div>[Design form here, based on the template below, or customized by yourself after the template removed]</div> <table align="center" border="0" cellpadding="0" cellspacing="0" class="tableListBorder" style="table-layout: fixed;"> <colgroup> <col width="130" /> <col /><!--hide4phone.start--> <col width="130" /> <col width="330" /><!--hide4phone.end--> </colgroup> <tbody> <tr> <td colspan="4" colspan4phone="2" dbf.source="" dbf.type="" style="background-color: lightyellow;"> <strong>[Brief Information]</strong></td> </tr> <tr> <td class="fieldLabel" style="text-align: center; width: 147px;"><span style="color: red;">*</span> username</td> <td id="username" style="width: 210px;"> </td> <!--show4phone.start--> </tr> <tr><!--show4phone.end--> <td class="fieldLabel" style="text-align: center; width: 63px;"><span style="color: red;">*</span> id</td> <td id="ID" style="width: 254px;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">项目名称</td> <td id="项目名称" style="width: 210px;"> </td> <td class="fieldLabel" style="text-align: center;">装置名称</td> <td id="装置名称" style="width: 254px;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">Customer Name</td> <td id="CustomerName" style="width: 210px;"> </td> <td class="fieldLabel" style="text-align: center;">E-NO/序列号</td> <td id="ENO号" style="width: 254px;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">产品描述</td> <td id="产品描述" style="width: 210px;"> </td> <td class="fieldLabel" style="text-align: center;">Remark</td> <td id="Remark" style="width: 254px;"> </td> </tr> <tr> <td class="fieldLabel" style="text-align: center;">Subject</td> <td id="subjectid" style="width: 210px;"> </td> <td class="fieldLabel" dbf.source="" dbf.type="" id="" style="text-align: center;"> </td> <td dbf.source="" dbf.type="" id="" style="width: 254px;"> </td> </tr> <tr> <td colspan="4" colspan4phone="2" dbf.source="" dbf.type="" style="background-color: lightyellow;"><strong> </strong><strong>[Detailed Information]</strong></td> </tr> </tbody> </table> <div style="text-align: center; margin: 20px 0;">        <input id="idslist" name="idslist" type="hidden" />  <input id="sql内容" name="sql内容" type="hidden" />                                                                 <strong> <input id="check" name="check" onclick="clickData()" type="button" value="check记录" /> </strong> <strong> <input id="check2" name="check2" onclick="clickData2()" type="button" value="下载结果" /> </strong></div> <!-- ==================== 移动端表格占位(暂不使用)==================== --><!-- ==================== 查询结果表格容器 ==================== --> <div id="resultTableContainer" style="margin-top: 20px; padding: 0 10px; min-height: 20px;"><!-- 动态表格将插入到这里 --></div> <div class="slide4phone2" id="reptable" style="display:none;"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="tableListBorder2" style="width: 1300px;"> </table> </div> <!-- ==================== 核心脚本:查询与渲染 ==================== --><script language="javascript"> function clickData() { if (window.__isQuerying) return; window.__isQuerying = true; try { var enonumber = $("ENO号")?.value ? $("ENO号").value().trim() : ""; if (!enonumber) { alert("请输入搜索内容"); return; } console.log("【原始输入】", enonumber); function escapeSql(str) { return String(str || '').replace(/'/g, "''"); } // ✅ 正确构建模糊匹配模式 const searchPattern = '%' + escapeSql(enonumber) + '%'; // ✅ 清洗字段中的各种隐藏字符 const cleanedField = ` REPLACE( REPLACE( REPLACE( REPLACE( ISNULL([ENO序列号], ''), CHAR(10), ''), CHAR(13), ''), CHAR(9), ''), ' ', '') `; var sql = ` SELECT TOP 100 Subject, Status, 申请人, 申请日期, 产品类别, 其他, type, 内勤, 系统, customer, ProjectName, DeviceName, 新产品, [ENO序列号], 目标价, 数量, 产地, 含税报价, HandlerRemark, Remark, 描述 FROM X_BPM_DWH_819_InquiryLines WHERE ${cleanedField} LIKE '${searchPattern}' ORDER BY 申请日期 DESC `; console.log("【执行SQL】", sql); var rawResult = service("common.js", "getDbsRecords", sql, "array"); let arr = parseServiceResult(rawResult); renderTable(arr); } catch (e) { console.error("查询失败", e); alert("错误:" + (e.message || e)); } finally { window.__isQuerying = false; } } /** * 安全解析 service 返回的结果 * 支持:合法JSON / 非法JSON / JS数组字面量 / 字符串化数组 / null等 */ function parseServiceResult(rawResult) { console.log("【原始返回类型】", typeof rawResult); console.log("【原始内容】", rawResult); // 情况1:已经是数组 if (Array.isArray(rawResult)) { console.log("✅ 已识别为原生数组"); return rawResult; } // 情况2:null/undefined/false if (rawResult == null || rawResult === 'null' || rawResult === 'undefined') { console.warn("⚠️ 返回为空值"); return []; } // 转为字符串处理 let str = String(rawResult).trim(); if (!str) { console.warn("⚠️ 返回空字符串"); return []; } // 情况3:可能是HTML错误页(常见于服务异常) if (str.startsWith('<') || str.includes('<html') || str.toLowerCase().includes('error') || str.includes('Exception')) { console.error("🔴 返回了HTML错误页!", str.substring(0, 200)); throw new Error('服务端错误,请检查SQL语法或联系管理员'); } /** * 数据清洗函数:修复各种非法字符 */ function clean(str) { return str .replace(/\\\\/g, '\\') // 修复多个反斜杠 .replace(/"/g, '\\"') // 先转义双引号 .replace(/'/g, '"') // 单引号 → 双引号 .replace(/\\"/g, '"') // 还原正常引号 .replace(/\\n/g, '\\n') // 显式换行 .replace(/\\r/g, '\\r') .replace(/\\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/\t/g, '\\t') .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, '') // 移除控制字符 .replace(/^"(\[.*\])"$/, '$1') // 去掉 "[...]" 外层引号 .replace(/^"(\{.*\})"$/, '$1') .replace(/,\s*}/g, '}') // 去除对象尾部逗号 .replace(/,\s*]/g, ']'); // 去除数组尾部逗号 } // 尝试多种解析方式 const parsers = [ // 方式1:直接JSON.parse () => JSON.parse(str), // 方式2:清洗后再解析 () => JSON.parse(clean(str)), // 方式3:作为JS表达式执行(仅限可信环境) () => new Function(`return (${str});`)(), // 方式4:进一步清理后尝试 () => JSON.parse(clean(str).replace(/""/g, '"').replace(/"\s+:/g, '":').replace(/:\s+"/g, ':"')) ]; for (let i = 0; i < parsers.length; i++) { try { const result = parsers[i](); if (Array.isArray(result)) { console.log(`✅ 第 ${i+1} 种方式解析成功`); return result; } // 兼容 { data: [...] } 结构 if (result && Array.isArray(result.data)) return result.data; if (result && Array.isArray(result.rows)) return result.rows; } catch (e) { console.warn(`📌 方式 ${i+1} 解析失败`, e.message); } } // 情况5:手动解析简单二维数组字符串 [[...],[...]] if (/^\[\s*$$[^$$]*$\s*(,\s*$$[^$$]*$)*\s*\]$/.test(str)) { try { console.log("🔍 检测到疑似二维数组字符串,尝试手动解析"); const rows = str.match(/$[^$$]*$/g) || []; return rows.map(row => { return row.replace(/^\[/, '').replace(/\]$/, '') .split(',') .map(field => field.trim().replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1')); }).filter(r => r.length > 0); } catch (e) { console.error("手动解析失败", e); } } // 所有方式都失败 console.error("🔴 所有解析方式均失败", { raw: rawResult, cleaned: clean(str) }); throw new Error('返回数据格式异常,无法解析。请检查SQL是否正确或联系开发人员。'); } /** * 渲染查询结果为表格 */ function renderTable(arr) { var container = document.getElementById("resultTableContainer"); if (!container) return; // 清空容器 container.innerHTML = ''; if (!arr || arr.length === 0) { container.innerHTML = ` <p style="text-align:center;color:#999;font-style:italic;padding:20px;"> 📭 未找到匹配的数据。 </p> `; return; } // 创建表格 var table = document.createElement('table'); table.className = 'tableListBorder'; table.style.width = '100%'; table.style.tableLayout = 'fixed'; table.setAttribute('border', '1'); table.setAttribute('cellpadding', '6'); table.setAttribute('cellspacing', '0'); table.style.fontFamily = 'Arial, sans-serif'; table.style.fontSize = '13px'; // 表头 var thead = document.createElement('thead'); var headerRow = document.createElement('tr'); var headers = [ "Subject", "Status", "申请人", "申请日期", "产品类别", "其他", "类型", "内勤", "系统", "客户", "项目名称", "装置名称", "新产品", "E-NO/序列号", "目标价", "数量", "产地", "含税报价", "处理备注", "备注", "描述" ]; headers.forEach(function(text) { var th = document.createElement('th'); th.style.backgroundColor = '#f5f5f5'; th.style.textAlign = 'center'; th.style.padding = '10px'; th.style.whiteSpace = 'nowrap'; th.style.fontWeight = 'bold'; th.textContent = text; headerRow.appendChild(th); }); thead.appendChild(headerRow); table.appendChild(thead); // 表体 var tbody = document.createElement('tbody'); arr.forEach(function(row, index) { if (!row || !Array.isArray(row) && typeof row !== 'object') { console.warn(`第 ${index} 行数据异常`, row); return; } var tr = document.createElement('tr'); Object.values(row).forEach(function(cell) { var td = document.createElement('td'); td.style.padding = '8px'; td.style.borderTop = '1px solid #eee'; td.style.wordBreak = 'break-word'; td.style.maxWidth = '200px'; td.textContent = cell == null ? '' : String(cell).trim(); tr.appendChild(td); }); tbody.appendChild(tr); }); table.appendChild(tbody); container.appendChild(table); console.log(`✅ 成功渲染 ${arr.length} 行数据`); } </script> <div id="resultTableContainer" style="margin-top: 20px; overflow-x: auto;"> </div> 完整修复以上 [ENO序列号] 匹配问题 数值不能完全匹配
最新发布
10-22
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值