You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Katalon向SQL数据库插入数据记录

在Katalon中通过自定义关键字向数据库插入数据记录

既然你已经实现了数据库连接的自定义关键字,我们可以基于现有连接快速实现数据插入操作,以下是具体步骤和代码示例:

1. 复用现有数据库连接

假设你现有的连接关键字返回的是java.sql.Connection对象,直接复用该连接执行插入,避免重复建立连接消耗资源。

2. 编写插入数据的自定义关键字

在Katalon自定义关键字类中新增插入方法,核心是通过PreparedStatement执行INSERT语句:

package com.yourcompany.keywords

import java.sql.Connection
import java.sql.PreparedStatement
import com.kms.katalon.core.annotation.Keyword

class DatabaseKeywords {
    // 你已有的数据库连接方法
    @Keyword
    def getDBConnection() {
        // 这里是你的原有连接逻辑,返回Connection对象
        // 示例参考:
        // Class.forName("com.mysql.cj.jdbc.Driver")
        // return DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db", "root", "password")
    }

    // 新增的插入数据方法
    @Keyword
    def insertRecord(String insertSql, List<Object> params = []) {
        Connection conn = null
        PreparedStatement pstmt = null
        try {
            conn = getDBConnection()
            pstmt = conn.prepareStatement(insertSql)
            
            // 绑定参数(避免SQL注入)
            params.eachWithIndex { param, idx ->
                pstmt.setObject(idx + 1, param)
            }
            
            // 执行插入,返回受影响行数
            return pstmt.executeUpdate()
        } catch (Exception e) {
            throw new Exception("插入数据失败: ${e.getMessage()}", e)
        } finally {
            // 强制关闭资源,防止连接泄漏
            pstmt?.close()
            conn?.close()
        }
    }
}

3. 在测试用例中调用插入关键字

在Katalon测试用例里,通过以下方式调用关键字完成数据插入:

// 定义带占位符的INSERT语句
def insertSql = "INSERT INTO customer(name, phone, register_date) VALUES (?, ?, ?)"

// 准备参数列表
def insertParams = ["张三", "13800138000", new Date()]

// 调用自定义关键字执行插入
def affectedRows = CustomKeywords.'com.yourcompany.keywords.DatabaseKeywords.insertRecord'(insertSql, insertParams)

// 验证插入结果
if (affectedRows > 0) {
    println "数据插入成功,共插入${affectedRows}条记录"
} else {
    throw new Exception("数据插入无生效记录")
}

关键注意事项

  • 优先使用PreparedStatement:用占位符绑定参数,杜绝SQL注入风险,同时提升重复执行效率。
  • 强制关闭资源:必须在finally块中关闭连接和语句对象,防止数据库连接池耗尽。
  • 事务控制(可选):如果需要保证数据一致性,可以在连接上开启事务,插入成功后提交,失败则回滚,可在关键字中扩展该逻辑。
  • 异常处理:根据测试场景调整异常抛出逻辑,比如插入失败时直接标记测试用例为失败。

内容的提问来源于stack exchange,提问作者user19610349

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 04:15:44