Lua脚本无法连接MySQL数据库,执行代码报错求助(Dragino网关/Arduino Yun)
Hey there, let's tackle this error you're seeing—this is a common issue when the Lua MySQL driver isn't properly installed or loaded on your device. Let's break down the fixes step by step:
1. Understand the Root Cause
The error attempt to index global 'luasql' (a nil value) means that when you ran require "luasql.mysql", Lua couldn't find the MySQL driver module. This usually happens because the module isn't installed on your Dragino/Yun device.
2. Install the Lua MySQL Driver via OpenWrt OPKG
Dragino Gateways and Arduino Yun run on OpenWrt-based systems, so we can use the OPKG package manager to install the missing driver:
- First, SSH into your device (use tools like PuTTY or your terminal).
- Run these commands to update package lists and install the driver:
If the above package name doesn't work, try the alternative package name for some OpenWrt versions:opkg update opkg install luasql-mysqlopkg install lua-luasql-mysql
3. Verify the Driver is in Lua's Search Path
Sometimes even after installation, Lua might not know where to find the driver. To check:
- Launch the Lua interactive shell by running
luain your SSH terminal. - Run these commands to print Lua's module search paths:
print(package.path) print(package.cpath) - Look for paths that point to where the MySQL driver is installed (usually
/usr/lib/lua/5.1/or/usr/share/lua/5.1/). If the driver's.sofile isn't in these paths, add the correct path to your script before requiring the module:-- Add this line at the very top of your script package.cpath = package.cpath .. ";/usr/lib/lua/5.1/?.so"
4. Fix Your Connection Code Syntax
Your original code has a syntax mistake in the connect call—you're not separating parameters correctly. Here's the corrected version (plus better Lua practices like using local variables):
-- Add the path fix here if needed package.cpath = package.cpath .. ";/usr/lib/lua/5.1/?.so" require "luasql.mysql" local env = assert(luasql.mysql(), "Failed to create MySQL environment") -- Note: Fixed the password typo (you had 'db_passwordL' with an extra L) local con = assert(env:connect( "nkt_development", -- Database name "db_user", -- DB username "db_password", -- DB password (correct this to your actual password) "172.31.10.60", -- DB host 3306 -- DB port ), "Failed to connect to MySQL")
5. Test the Connection
After making these changes, run your script again. If you still run into issues, test step-by-step in the Lua interactive shell:
- Run
require "luasql.mysql"—if no error, the driver is loaded. - Run
local env = luasql.mysql()—check if this returns a valid environment object. - Run the
connectcall with your actual DB credentials to debug any connection-specific issues.
内容的提问来源于stack exchange,提问作者Christian Schumacher

