oxmysql插入数据报Unknown column 'NaN'错误求助
问题原因分析
根据错误日志和传入参数,核心问题出在两个方面:
- SQL语句使用字符串拼接而非参数绑定:如果你的代码用
string.format或直接拼接字符串生成SQL,当某个变量未初始化(比如位置名称为空)时,会被转换为NaN并直接拼进SQL语句。数据库会将无引号包裹的NaN识别为列名,从而抛出「Unknown column 'NaN' in 'field list'」错误。 - 参数未做校验:传入的参数中存在
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类型,支持存储浮点坐标
验证方法
- 执行
savelocation命令时不输入名称,确认能收到错误提示 - 正常输入名称保存位置,检查数据库是否成功插入数据
- 查看oxmysql日志,确认参数列表中无
NaN或无效null值
内容的提问来源于stack exchange,提问作者Frish
相关产品推荐
相关产品推荐

