How to create a registration app using Python and database

Python has excellent database support built into its standard library, so you can create and interact with a database without having to rely on an external framework like Django ORM.

Building this app will help you better understand how to create a database table and fill it with data.

How to create a registration app using Python and database Picture 1How to create a registration app using Python and database Picture 1

Python has excellent database support built into its standard library, so you can create and interact with a database without having to rely on an external framework like Django ORM.

SQLite is lightweight and easily integrated into Python. Let's explore the basic rules of database programming in Python by developing a simple user registration app.

How to create database in Python

To create and interact with a database in Python, you need two main elements: connection and cursor .

A connection helps you connect to an existing database or create a new one. Here's how to create a database connection in Python with SQLite:

import sqlite3 # Kết nối một database mới conn = sqlite3.connect('path/to/database.db') # Đóng kết nối conn.close()

The connect() method gets the path to the existing database. If there is no database in the specific path, it will create a new one. You should close the database connection when you have finished interacting with that database.

A pointer helps you interact with the connected database. You will use a cursor to implement SQL queries in your Python program. Here's how to create a cursor:

cursor = conn.cursor() # Đóng con trỏ cursor.close()

You can create a cursor by calling the cursor() method when opening the connection object.

How to run a database transaction in Python

Using cursors, you can run commands, queries, or SQL scripts to read or write data or change the database structure.

There are currently three main methods that you can use to deploy a database transaction.

1. Cursor.execute . This method will run a single command. Here's how you use it:

cursor.execute(""" CREATE TABLE IF NOT EXISTS users ( name TEXT, age INTEGER ) """)

This code calls the execute method on a cursor, converting it to a string containing an SQL statement.

2. Cursor.executemany . This method allows you to run the same SQL statement multiple times, but each time, the parameters will be different. It takes two arguments: the SQL command and an iterable. A good way to use it is to insert multiple objects into the database at the same time:

data = [ ('Alice', 25), ('Bob', 30), ('Charlie', 22) ] cursor.executemany("""INSERT INTO users (name, age) VALUES (?, ?)""", data)

The above code uses the executemany method to insert values ​​into the database multiple times.

3. Cursor.executescript . As the name suggests, this method will deploy an SQL script for you. You can write SQL commands in another file and run them with the executescript method :

with open("path/to/script.sql") as file: sql_script = file.read() cursor.executescript(sql_script)

How to build a registration app using Python and SQLite3

The logic behind the registration app involves retrieving user information using Python and storing them in a database. These steps will show you how to create a simple registration system with Python and SQLite3.

Step 1: Connect to an existing database or create a new one

Start by creating a database for your application or connecting to an existing database:

 

import sqlite3 conn = sqlite3.connect('database.db') cursor = conn.cursor() # Code của ứng dụng ở đây cursor.close() conn.close()

The above code creates a connection object and a pointer that interacts with the connected database.

Step 2: Create a table for users

You need a table containing the data the user provides when registering. Here is a new creation using a pointer:

cursor.execute(""" CREATE TABLE IF NOT EXISTS users ( first_name TEXT, last_name TEXT, email TEXT UNIQUE, password TEXT ) """) conn.commit()

This code will create a table named user s if it does not exist in the database. It creates 4 columns in the table to contain user information. This email field is unique to prevent users from creating multiple accounts with the same email.

Calling conn.commit is important to push the query into the database. Without it, nothing will change in the database.

Step 3: Collect user data

Python functions make code reuse easy, so a good idea here is to create a function that handles the registration feature. This function collects the user's full name, email and password.

def register_user(): first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") email = input("Enter your email: ") password1 = input("Enter your password: ") password2 = input("Confirm your password: ")

Step 4: Check the accuracy of the password

Edit the registrar_user function to ensure the user enters the same password twice. If they don't, you should prompt them to re-enter their password. You can achieve that using a loop like this:

def register_user(): first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") email = input("Enter your email: ") while True: password1 = input("Enter your password: ") password2 = input("Confirm your password: ") # Kiểm tra độ chính xác của mật khẩu if password1 == password2: print("You have successfully registered!") break else: print("Your passwords must match")

With this change, users cannot register unless the password matches.

Step 5: Check the uniqueness of the email

The SQL command creates a user table that identifies the email field as unique. This means the database will return an error if the user registers with an email that already exists. To take appropriate action, you need to handle Python exceptions:

def register_user(): first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") while True: email = input("Enter your email: ") password1 = input("Enter your password: ") password2 = input("Confirm your password: ") # Kiểm tra độ chính xác của mật khẩu if password1 == password2: try: print("You have successfully created an account.") break except sqlite3.IntegrityError: print("Error: This email is already registered.") else: print("Your passwords must match.")

 

This code uses a try-except block to handle errors that will occur from duplicate emails. If the database throws an IntegrityError , the while loop will continue, prompting the user to enter another email address.

Step 6: Insert user data into the database

Now that you have collected and verified user data, it's time to add it to the database. You can use an SQL query to do this. Edit the try-except block as follows:

try: cursor.execute(""" INSERT INTO users (first_name, last_name, email, password) VALUES (?, ?, ?, ?) """, (first_name, last_name, email, password2)) conn.commit() print("You have successfully created an account.") break except sqlite3.IntegrityError: print("Error: This email is already registered.")

In the edited try-except block, the cursor implements an SQL insert operation. Finally, the conn.commit method commits the SQL operation to this database.

If you have followed all the steps above, you will have an application that registers users and saves them in the database. You can use an app like DB Browser for SQLite to view the contents of the database:

How to create a registration app using Python and database Picture 2How to create a registration app using Python and database Picture 2

Hope this article is useful to you!

5 ★ | 1 Vote