English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
本文主要为大家介绍 Lua 数据库的操作库:LuaSQL。他是开源的,支持的数据库有:ODBC, ADO, Oracle, MySQL, SQLite 和 PostgreSQL。
本文为大家介绍MySQL的数据库连接。
LuaSQL 可以使用 LuaRocks 来安装可以根据需要安装你需要的数据库驱动。
LuaRocks 安装方法:
$ wget http://luarocks.org/releases/luarocks-2.2.1.tar.gz $ tar zxpf luarocks-2.2.1.tar.gz $ cd luarocks-2.2.1 $ ./configure; sudo make bootstrap $ sudo luarocks install luasocket $ lua Lua 5.3.0 Copyright (C) 1994-2015 Lua.org, PUC-Rio > require "socket"
Window 下安装 LuaRocks:https://github.com/keplerproject/luarocks/wiki/Installation-instructions-for-Windows
다른 데이터베이스 드라이버 설치:
luarocks install luasql-sqlite3 luarocks install luasql-postgres luarocks install luasql-mysql luarocks install luasql-sqlite luarocks install luasql-odbc
또한 소스 코드 설치 방식을 사용할 수도 있습니다. Lua Github 소스 코드 주소:https://github.com/keplerproject/luasql
Lua가 MySql 데이터베이스에 연결됨:
require "luasql.mysql" --5.2 버전 이후로, require는 더 이상 전역 변수를 정의하지 않으며, 반환 값을 저장해야 합니다. --필요하게 되면: --luasql = require "luasql.mysql" --환경 객체 생성 env = luasql.mysql() --데이터베이스 연결 conn = env:connect("데이터베이스 이름", "사용자 이름", "비밀번호", "IP 주소", 포트) --데이터베이스编码 설정 conn:execute"SET NAMES UTF8" --데이터베이스 작업 실행 cur = conn:execute("select * from role row = cur:fetch({}, "a") --파일 객체 생성 file = io.open("role.txt", "w+"); while row do var = string.format("%d %s\n", row.id, row.name) print(var) file:write(var) row = cur:fetch(row, "a") end file:close() --파일 객체 닫기 conn:close() --데이터베이스 연결 닫기 env:close() --데이터베이스 환경 닫기