Зміст курсу
SQL in Python Projects
SQL in Python Projects
Creation Operations
Insertion Operations
Creation operations in SQLite involve the process of adding new records or rows to an existing database table. These operations allow you to populate your tables with data. Let's see how insertion operations work within the concept of creating a database.
Inserting a Record
To create a new record within a table, you can use the SQL INSERT INTO
statement. Here's a basic example:
Be careful because this code considers working on an already existing table. If you don't have a users
table in your database, then you need to create one.
To avoid the error, you need to create a table in the database with the name users
and fields username
and email
. Only after that can you add records to this table.
Code description
- We connect to the database;
- Create a cursor to execute SQL queries;
- Use an
INSERT INTO
query to insert a new record into the "users" table, specifying the column names ("username" and "email") and providing values using placeholders (?
); - Execute the query with
cursor.execute(insert_query, user_data)
and pass the data as a tuple; - Save the changes to the database using
connection.commit()
; - Finally, close the database connection.
Insertion operations are an integral part of the "Create" aspect in CRUD, allowing you to create new data within your database tables.
Дякуємо за ваш відгук!