To use SQLite on a Raspberry Pi with Thonny, you can follow these steps:
Open Thonny IDE: If you’re using Raspberry Pi OS with a desktop environment, Thonny comes pre-installed. You can find it under ‘Programming’ in the main menu1.
Install SQLite: If it’s not already installed, you can install SQLite using the package manager with the command:
sudo apt install sqlite3
Create a New Python File: In Thonny, create a new Python file where you’ll write your SQLite code.
Import SQLite3: At the beginning of your Python script, import the sqlite3 module:
Python
import sqlite3
Connect to a Database: Use the connect method to connect to an SQLite database. If the database does not exist, SQLite will create it for you:
Python
Execute SQL Commands: You can now execute SQL commands using the cursor object. For example, to create a table:
Python
Commit Changes: After executing your commands, commit the changes to the database:
Python
connection.commit()
Close the Connection: Once you’re done with the database operations, close the connection:
Python
connection.close()
Remember to replace 'example.db' with the path to your actual database file. If you encounter any issues, make sure the path to the database is correct and accessible.
https://raspberrytips.com/thonny-ide-raspberry-pi/
Last edited by Moti Barski on Thu Mar 14, 2024 1:40 pm; edited 1 time in total
Open Thonny IDE: If you’re using Raspberry Pi OS with a desktop environment, Thonny comes pre-installed. You can find it under ‘Programming’ in the main menu1.
Install SQLite: If it’s not already installed, you can install SQLite using the package manager with the command:
sudo apt install sqlite3
Create a New Python File: In Thonny, create a new Python file where you’ll write your SQLite code.
Import SQLite3: At the beginning of your Python script, import the sqlite3 module:
Python
import sqlite3
Connect to a Database: Use the connect method to connect to an SQLite database. If the database does not exist, SQLite will create it for you:
Python
Code:
connection = sqlite3.connect('example.db')
cursor = connection.cursor()
Execute SQL Commands: You can now execute SQL commands using the cursor object. For example, to create a table:
Python
Code:
cursor.execute('''CREATE TABLE IF NOT EXISTS stocks
(date text, trans text, symbol text, qty real, price real)''')
Commit Changes: After executing your commands, commit the changes to the database:
Python
connection.commit()
Close the Connection: Once you’re done with the database operations, close the connection:
Python
connection.close()
Remember to replace 'example.db' with the path to your actual database file. If you encounter any issues, make sure the path to the database is correct and accessible.
https://raspberrytips.com/thonny-ide-raspberry-pi/
Last edited by Moti Barski on Thu Mar 14, 2024 1:40 pm; edited 1 time in total