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

oxmysql插入数据报Unknown column 'NaN'错误求助

问题原因分析

根据错误日志和传入参数,核心问题出在两个方面:

  1. SQL语句使用字符串拼接而非参数绑定:如果你的代码用string.format或直接拼接字符串生成SQL,当某个变量未初始化(比如位置名称为空)时,会被转换为NaN并直接拼进SQL语句。数据库会将无引号包裹的NaN识别为列名,从而抛出「Unknown column 'NaN' in 'field list'」错误。
  2. 参数未做校验:传入的参数中存在null(对应第二个参数),说明代码未对必填字段(比如保存的位置名称)做非空校验,导致无效值流入数据库操作。
修复方案

1. 强制使用oxmysql参数绑定替换字符串拼接

oxmysql支持用?作为占位符实现参数绑定,会自动处理参数类型转义和SQL注入风险,彻底避免NaN被误判为列名的问题。

修复后的savelocation命令示例:

RegisterCommand('savelocation', function(source, args)
    local xPlayer = ESX.GetPlayerFromId(source)
    if not xPlayer then return end

    -- 校验必填的位置名称
    local locationName = args[1]
    if not locationName or locationName == '' then
        TriggerClientEvent('chat:addMessage', source, {
            color = {255, 0, 0},
            args = {'错误', '请输入要保存的位置名称!'}
        })
        return
    end

    local license = xPlayer.getIdentifier('license')
    local ped = GetPlayerPed(source)
    local coords = GetEntityCoords(ped)
    local heading = GetEntityHeading(ped)

    -- 使用参数绑定执行插入
    MySQL.insert('INSERT INTO player_locations (license, name, x, y, z, heading) VALUES (?, ?, ?, ?, ?, ?)', {
        license,
        locationName,
        coords.x,
        coords.y,
        coords.z,
        heading
    }, function(affectedRows)
        if affectedRows > 0 then
            TriggerClientEvent('chat:addMessage', source, {
                color = {0, 255, 0},
                args = {'成功', '位置「' .. locationName .. '」已保存!'}
            })
        end
    end)
end, false)

2. 补全参数校验逻辑

在所有数据库操作前,对传入参数做合法性校验:

  • 检查玩家标识符是否有效
  • 检查必填字段(如位置名称)是否非空
  • 确保坐标值为合法数字(可通过type(coords.x) == 'number'验证)

3. 核对数据库表结构

确认player_locations表的字段定义:

  • name字段设置为NOT NULL(避免空值插入)
  • x/y/z/heading字段设置为FLOAT或DOUBLE类型,支持存储浮点坐标
验证方法
  1. 执行savelocation命令时不输入名称,确认能收到错误提示
  2. 正常输入名称保存位置,检查数据库是否成功插入数据
  3. 查看oxmysql日志,确认参数列表中无NaN或无效null值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 17:05:55