How to Connect to SQLite with Lua
Step by step from installation to database connection.
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.
1. Required packages
First of all let’s install the necessary dependencies
Note: Even if you have already installed it, I recommend reinstalling, for this the parameter:
Some package names may be different in your distro, use search in your package manager for the corresponding names.
2. Check that both are working normally:
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
3. Now let’s install LuaSQL with Luarocks
Check if it was installed normally by listing with
Similar output will be:
That is, listed the luasql-sqlite3 normally and the
sqlite3.sofile is in the path:
4. Now let’s make it possible for
package.path to find the SQLite package installed by Luarocks
To do this, create a symbolic link with the command below:
If when you run this command:
ls /usr/local/lib/luaif the output is not 5.1 you will have to change the symbolic link of the
luacommand 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 your
luacommand 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:executeyou must enter the SQLite command you want, it can be:
- The variables have almost the same names as the columns, but this is not a rule.