Insert LUA variables into Sqlite3 Database
In this short tutorial, We will try to insert lua variables into Sqlite3 database using Lua programming language.
Installing Sqlite3 in Ubuntu server :
First of all, install the Sqlite3 in ubuntu server using the following command
1 |
apt-get install sqlite3 |
Create Sqlite3 Database :
Then create one Sqlite3 database using the following command.
1 |
sqlite3 asterisk.db |
Now asterisk.db is created in the present folder. you can connect to that database just by typing following command.
1 2 3 4 |
root@ubuntu:~# sqlite3 asterisk.db SQLite version 3.11.0 2016-02-15 17:29:24 Enter ".help" for usage hints. sqlite> |
Now you have access to the SQLITE3 CLI ( Command line interface )
Creating Tables :
Now i’m going to create one sample table. My table schema is very simple with four columns. Here is the schema.
1 |
CREATE TABLE "MOS" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "unixts" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, "MOS" FLOAT NOT NULL, "is_processed" INT NOT NULL ); |
Inserting Values to Sqlite3 using Lua Sqlite3 module:
Here is the small program to insert the variables into Sqlite3 Database using Lua lsqlite3 module.
1 2 3 4 5 6 7 8 9 10 |
sqlite3 = require "lsqlite3" -- Importing Data to SQLite MOS = 4.3 db = sqlite3.open './asterisk.db' local sql = "insert into MOS( MOS, is_processed) values( '"..MOS.."' , 0)" local res = assert(db:execute(sql)) print(sql) db:close() |
The line SQL will create our insert query and where MOS is variable. we need to use lua .. operator.
Now go ahead and run the program using the following command.
1 |
lua sqlite3.lua |
Now check the database,
1 2 3 4 5 6 |
root@ubuntu:~# sqlite3 ./lua/asterisk.db SQLite version 3.11.0 2016-02-15 17:29:24 Enter ".help" for usage hints. sqlite> select * from MOS; 1|2017-09-14 12:29:45|4.3|0 sqlite> |
You can see our MOS value is successfully inserted into the database.