PowerBuilder 19插入新文章时出现不存在的主键重复错误
问题分析与修复方案
核心问题定位
- 新建按钮重复插入行:脚本中连续调用了两次
InsertRow(0),每次点击「新建」会在数据窗口中添加两行记录。未被编辑的第一行可能保留空值或旧主键值,后续提交时触发重复主键冲突。 - 保存按钮未处理更新状态:执行
update()后未调用ResetUpdate(),数据窗口会持续标记之前的更新行,再次提交时重复发送旧数据。 - 保存逻辑缺失错误检查:未验证
update()的返回值,也未捕获完整的SQL错误信息,无法及时定位问题根源。
修复步骤
1. 修正「新建」按钮脚本(移除重复插入)
long ll_new_row // 仅插入一行新记录 ll_new_row = dwc_article.InsertRow(0) dwc_article.ScrollToRow(ll_new_row) // 设置创建日期 date ld_date_creation = Today() string ls_formatted_date = String(ld_date_creation, "yyyy-mm-dd") dwc_article.SetItem(ll_new_row, "date_de_creation", ls_formatted_date) // 解锁可编辑字段 dwc_article.Modify("reference.Protect='0'") dwc_article.Modify("name.Protect='0'") dwc_article.Modify("prix.Protect='0'") dwc_article.Modify("date_de_creation.Protect='1'")
2. 优化「保存新文章」按钮脚本(完善错误处理与状态重置)
dwc_article.AcceptText() // 检查是否有需要保存的修改 if dwc_article.GetItemStatus(0, 0, Primary!) = ItemNewModified! or dwc_article.GetItemStatus(0, 0, Primary!) = ItemModified! then int li_update_ret li_update_ret = dwc_article.Update(True, False) // 执行更新,不自动提交事务 if li_update_ret = 1 then COMMIT USING SQLCA; if SQLCA.SQLCode = 0 then MessageBox("成功", "文章已成功添加。") dwc_article.ResetUpdate() // 重置数据窗口更新状态,避免重复提交 dwc_report.Retrieve() else ROLLBACK USING SQLCA; MessageBox("错误", "提交失败:" + SQLCA.SQLErrText) end if else ROLLBACK USING SQLCA; MessageBox("错误", "数据更新失败,请检查输入是否合法。") end if else MessageBox("提示", "没有需要保存的修改。") end if
额外排查建议
- 验证数据库主键:直接执行SQL
SELECT * FROM 你的表名 WHERE reference = '冲突值',确认数据库中是否真的存在该主键,排除数据不一致问题。 - 检查数据窗口更新属性:确保
reference字段被设置为「主键」,且插入操作时允许用户输入该字段。 - 更新后重置状态:在编辑现有文章并保存后,调用
dwc_article.ResetUpdate(),避免残留未提交的修改记录。
内容的提问来源于stack exchange,提问作者Hatem Moalla
相关产品推荐
相关产品推荐

