Working with SQLite Databases¶
SQLite is a simple database that's perfect for learning. You don't need a separate server—it's just a file on your computer. Free Pascal makes it easy to work with SQLite databases.
What is CRUD?¶
CRUD stands for the four basic things you can do with data:
- Create - Add new records to the database
- Read - Get data from the database
- Update - Change existing records
- Delete - Remove records
Setting Up SQLite¶
First, you need the SQLite library. Most systems already have it installed. In your Free Pascal code, you'll use the sqlite3 unit.
Installing SQLite3 Libraries¶
The sqlite3 unit requires the SQLite3 libraries to be installed on your system:
- Windows: Download the SQLite3 DLL from https://sqlite.org/download.html. The DLL must be in a path that can be found by your executable (such as the same directory as your program, or in your system PATH).
- Linux: Use your distribution's package manager to install SQLite3 libraries:
- Ubuntu/Debian:
sudo apt-get install libsqlite3-0 - Fedora/RHEL:
sudo dnf install sqlite-libs - Arch:
sudo pacman -S sqlite - macOS: SQLite3 is typically pre-installed, but you can install or update it via Homebrew:
brew install sqlite
Simple Database Example: Student Records¶
Here's a complete program that creates a database, adds students, reads them, updates one, and deletes one.
How It Works¶
-
Open Database -
sqlite3_open('students.db', @DB)opens the file (or creates it if it doesn't exist) -
Create Table - The
CREATE TABLEcommand sets up the structure. Each student has: -id- A unique number (automatically increases) -name- Text for the student's name -age- A number for age -
Create (INSERT) - Add new records with
INSERT INTO students VALUES (...) -
Read (SELECT) - Get data with
SELECTand loop through results withsqlite3_step -
Update - Change existing records with
UPDATE ... SET ... WHERE -
Delete - Remove records with
DELETE FROM ... WHERE
Getting Column Values¶
When you read from the database, you get back different types:
{ Get different data types from a result }
sqlite3_column_int(Stmt, 0) { Get an integer }
sqlite3_column_text(Stmt, 1) { Get text }
sqlite3_column_double(Stmt, 2) { Get a decimal number }
Common Mistakes to Avoid¶
- Remember to use
sqlite3_finalize(Stmt)after reading results, so you don't waste memory - Use quotes correctly: single quotes
'inside SQL, double quotes"in Pascal strings - Always close the database with
sqlite3_close(DB)when done
The File¶
The database is saved as students.db in the same folder as your program. You can open it with database viewer tools to see the data.
Next Steps¶
- Try changing the table structure (add more columns like email or grade)
- Use
WHEREconditions to find specific students - Try using
ORDER BYto sort results