How to Create a Registration App With Python and a Database

Trending 3 weeks ago

Python has fantabulous database support built into its modular library, truthful you tin create and interact pinch a database without relying connected outer frameworks for illustration nan Django ORM.

SQLite is lightweight and easy to merge pinch Python. Discover nan basal principles of database programming successful Python pinch a elemental personification registration app.

How to Create a Database successful Python

To create and interact pinch a database successful Python, you request 2 main things: a connection and a cursor.

A relationship helps you link to an existing database aliases create a caller one. Here's really to create a database relationship successful Python pinch SQLite:

import sqlite3


conn = sqlite3.connect('path/to/database.db')


conn.close()

The connect() method takes successful nan way to an existing database. If location is nary database astatine nan specified path, it will create one. You should adjacent your database relationship erstwhile you're done interacting pinch nan database.

A cursor helps you interact pinch nan connected database. You will usage a cursor to execute SQL queries wrong your Python program. Here's really to create a cursor:

cursor = conn.cursor()


cursor.close()

You tin create a cursor by calling nan cursor() method connected an unfastened relationship object.

How to Execute a Database Transaction successful Python

Using a cursor, you tin tally SQL statements, queries, aliases scripts, to publication aliases constitute data, aliases change nan database structure.

There are 3 main methods you tin usage to execute a database transaction.

  1. Cursor.execute. This method will tally a azygous SQL statement. Here's really you usage it: cursor.execute("""
        CREATE TABLE IF NOT EXISTS users (
            name TEXT,
            age INTEGER
        )
    """)
    This codification calls nan execute method connected a cursor, passing it a drawstring containing an SQL statement.
  2. Cursor.executemany. This method lets you tally nan aforesaid SQL connection much than once, pinch different parameters each time. It takes 2 arguments: nan SQL connection and an iterable. A bully usage for it is to insert respective objects into nan database astatine once: information = [
        ('Alice', 25),
        ('Bob', 30),
        ('Charlie', 22)
    ]

    cursor.executemany("""INSERT INTO users (name, age) VALUES (?, ?)""", data)

    The supra codification uses nan executemany method to insert values into nan database aggregate times.

    Note nan ? placeholders successful nan SQL statement. The executemany method will switch these pinch nan corresponding values for each object.

  3. Cursor.executescript. As nan sanction suggests, this method will execute an SQL book for you. You tin constitute your SQL statements successful a different record and tally them pinch nan executescript method: with open("path/to/script.sql") as file:
    sql_script = file.read()

    cursor.executescript(sql_script)

How to Build a Registration App With Python and SQLite3

The logic down a registration app involves getting nan user's accusation pinch Python and storing them successful a database. These steps will show you really to create a elemental registration strategy pinch Python and SQLite3.

Step 1: Connect to an Existing Database aliases Create a New One

Start by creating a database for your app aliases connecting to an existing one:

import sqlite3

conn = sqlite3.connect('database.db')

cursor = conn.cursor()

cursor.close()

conn.close()

The codification supra creates a relationship entity and a cursor to interact pinch nan connected database.

Step 2: Create a Table for Users

You request a array to shop nan information users will supply erstwhile registering. Here's really to create 1 pinch your cursor:

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

conn.commit()

This codification will create a array called users if it doesn't beryllium successful your database. It creates 4 columns successful nan array to clasp personification information. The email section is unsocial to forestall users from creating aggregate accounts pinch nan aforesaid email.

The telephone to conn.commit is important to perpetrate nan query into nan database. Without it, location will beryllium nary changes to nan database.

If you usage nan executescript method, you tin adhd nan COMMIT keyword astatine nan extremity of your SQL file, truthful you don't person to telephone conn.commit.

Step 3: Collect User Data

Python functions make it easy to reuse code, truthful it's a bully thought to create a usability to grip nan registration feature. This usability collects nan user's first name, past name, email, and password.

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

Step 4: Check Password Correctness

Modify nan register_user usability to guarantee nan personification enters nan aforesaid password twice. If they don't you should punctual them to re-enter nan password. You tin execute that pinch a loop for illustration this:

def register_user():
    first_name = input("Enter your first name: ")
    last_name = input("Enter your past name: ")
    email = input("Enter your email: ")

    while True:
        password1 = input("Enter your password: ")
        password2 = input("Confirm your password: ")

        
        if password1 == password2:
            print("You person successfully registered!")
            break
        else:
            print("Your passwords must match")

With this change, a personification cannot registry unless their passwords match.

Step 5: Check Email Uniqueness

The SQL connection that creates nan users array defines nan email section arsenic unique. This intends nan database will return an correction if a personification signs up pinch an email that already exists. To enactment appropriately, you request to handle nan Python exception:

def register_user():
    first_name = input("Enter your first name: ")
    last_name = input("Enter your past name: ")

    while True:
        email = input("Enter your email: ")
        password1 = input("Enter your password: ")
        password2 = input("Confirm your password: ")

        
        if password1 == password2:
            try:
                print("You person successfully created an account.")
                break
            except sqlite3.IntegrityError:
                print("Error: This email is already registered.")
        else:
            print("Your passwords must match.")

This codification uses nan try-except artifact to grip nan correction that will hap from copy emails. If nan database throws an IntegrityError, nan while loop will continue, prompting nan personification to participate a different email address.

For this sample app, it's safe to presume that an IntegrityError will only hap arsenic a consequence of a copy email address. In a existent app, you will astir apt usage much precocious error-handling to cater for different problems that mightiness occur.

Step 6: Insert nan User's Data Into nan Database

Now that you've collected and verified nan user's data, it's clip to adhd it to nan database. You tin usage an SQL query to do so. Modify your try-except artifact for illustration this:

try:
    cursor.execute("""
        INSERT INTO users (first_name, last_name, email, password)
        VALUES (?, ?, ?, ?)
    """, (first_name, last_name, email, password2))

    conn.commit()
    print("You person successfully created an account.")
    break
except sqlite3.IntegrityError:
    print("Error: This email is already registered.")

In nan modified try-except block, nan cursor executes an SQL insert operation. Finally, nan conn.commit method commits nan SQL cognition to nan database.

If you followed each nan steps above, you should person an exertion that registers users and saves them to nan database. You tin usage an app for illustration DB Browser for SQLite to position nan contents of your database:

The DB Browser for SQLite app showing a azygous personification grounds successful a database table.

Using Databases Instead of Collection Types

For elemental databases, you whitethorn find it easier to rotation your ain code. However, arsenic your exertion grows and your database becomes much complex, see utilizing a instrumentality for illustration Django ORM to simplify nan task.

To proceed practicing your low-level database skills, effort implementing a login strategy to complement nan registration program.

Source Tutorials
Tutorials