lua 连接mysql数据库实现增删改查操作(linux下示例)

(1)linux下连接数据库: mysql -u root -p,-u 指定登录用户,-p 指定密码。

[danni@vm-bestgame-18 develop]$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1356
Server version: 5.1.73 Source distribution

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

(2)show databases; 显示所有数据库

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| DanniDB            |
| mysql              |
| test               |
+--------------------+
6 rows in set (0.00 sec)

(3)创建一个新的数据库来进行操作:create databse DanniDB;

mysql> create database DanniDB;
Query OK, 1 row affected (0.00 sec)

(4)选择使用刚创建的数据库:use DanniDB;

mysql> use DanniDB;
Database changed

(5)创建一个表:

mysql> create table RoleInfo(
    -> ID int,
    -> name varchar(30),
    -> primary key(ID)
    -> );

(6)查看所有表 show tables;

mysql> show tables;
+-------------------+
| Tables_in_DanniDB |
+-------------------+
| RoleInfo          |
+-------------------+
1 row in set (0.00 sec)

(7)查看表结构 desc RoleInfo;

mysql> desc RoleInfo;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| ID    | int(11)     | NO   | PRI | 0       |       |
| name  | varchar(30) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

(8)把主键设置为自动增长 alter table RoleInfo change ID ID int auto_increment;

mysql> alter table RoleInfo change ID ID int auto_increment;
Query OK, 2 rows affected (0.02 sec)
Records: 2  Duplicates: 0  Warnings: 0







通过lua操作数据库首先要确保已经安装lua、mysql、LuaRocks、luasql-mysql。具体安装这里不再书写,网上有很多例子。可以去参考

下面即是一个通过lua操作数据库的示例代码。

luasql = require "luasql.mysql"

--创建环境对象
env = luasql.mysql();

--连接数据库      数据库名  用户名  密码  IP地址   端口
conn = env:connect("DanniDB","root","","127.0.0.1",3306);

--设置数据库的编码格式
conn:execute"SET NAMES UTF8"


--执行数据库插入操作
addName = "heihei";
cur = conn:execute("select * from RoleInfo where name = "..addName);    --先判断是否已经插入过改名字的数据
if cur ~= 1 then
    cur = conn:execute("insert into RoleInfo(name) values("..addName..")");
    if cur == 1 then
        print("插入数据成功");
    end
else 
    print("已经插入过名字为"..addName.."的数据");
end

--执行数据库查询操作
cur = conn:execute("select * from RoleInfo");
row = cur:fetch({},"a");
while row do
    var = string.format("%d %s", row.ID, row.name);
    print(var);

    row = cur:fetch(row,"a")
end

conn:close();
env:close();

你可能感兴趣的:(Lua)