Connecting to a database in particular SQLite is essential to develop local and even online applications.
We also have a complete guide to using Lua for beginners at this link .
In this article we will see how to connect to SQLite using Lua using a step by step from installation to database connection.
For this we will use Ubuntu 21.04 as a reference, but you can change package names, directory paths according to your distribution or operating system.
First of all let’s install the necessary dependencies
Note: Even if you have already installed it, I recommend reinstalling, for this the parameter:
--reinstall
Some package names may be different in your distro, use search in your package manager for the corresponding names.
Check command and version.
Change the interpreter to 5.1 by modifying your interpreter’s symlink
If you are on another Ubuntu distribution or version, create a symlink directly, eg
sudo ln -sf /usr/bin/lua5.1 /usr/bin/lua
Check if it was installed normally by listing with luarocks
Similar output will be:
That is, listed the luasql-sqlite3 normally and the
sqlite3.so
file is in the path:/usr/local/lib/luarocks/rocks
package.path
to find the SQLite package installed by LuarocksTo do this, create a symbolic link with the command below:
NOTE
If when you run this command:
ls /usr/local/lib/lua
if the output is not 5.1 you will have to change the symbolic link of thelua
command to the version that appears as we did in step 3, if more than one appears there will be no problem, but if the version number of yourlua
command does not exist you will only be able to use the interpreter for the corresponding version of those available when listing this cited directory.
To test we are going to use a test-ready database that I created and to get it just download it with wget with the command below:
Now let’s create the database.lua
file with the code Lua below and then we will explain some parts of it:
The output should return data from the fields of the informed table.
db:execute
you must enter the SQLite command you want, it can be: CREATE
, UPDATE
, DELETE
…