1. 程式人生 > >lua 連線mysql資料庫實現增刪改查操作(linux下示例)

lua 連線mysql資料庫實現增刪改查操作(linux下示例)

(1)linux下連線資料庫: mysql -u root -p,-u 指定登入使用者,-p 指定密碼。

[[email protected]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();