[파이썬] SQLite 데이터베이스 생성과 연결

SQLite is a lightweight, serverless, and self-contained relational database management system. It is widely used for embedded database applications and disk-based applications that require a small footprint. In this blog post, we will learn how to create and connect to an SQLite database in Python.

Prerequisites

To follow along with this tutorial, you will need the following:

Creating a SQLite Database

To create an SQLite database in Python, you need to import the sqlite3 module and use the connect function to establish a connection to the database. The connect function takes the name of the database file as a parameter. If the database file does not exist, it will be created.

import sqlite3

# Create a connection to the database
conn = sqlite3.connect('mydatabase.db')

In the above code, we create a connection to a database named ‘mydatabase.db’. This will either connect to an existing database file or create a new one if it doesn’t exist.

Creating Tables

Once connected to the database, you can execute SQL commands to create tables and perform other operations. First, we need to create a cursor object using the cursor method of the connection object.

# Create a cursor object
cursor = conn.cursor()

# Execute SQL commands
cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        email TEXT NOT NULL
    )
''')

# Save the changes
conn.commit()

# Close the connection
conn.close()

In the above code, we create a table named ‘users’ with three columns: ‘id’ (integer, primary key), ‘name’ (text, not null), and ‘email’ (text, not null). The execute method is used to execute the SQL command. We use IF NOT EXISTS to ensure that the table is created only if it doesn’t already exist.

After executing the SQL command, we call the commit method to save the changes. Finally, we close the connection using the close method.

Connecting to an Existing Database

If the database file already exists, you can connect to it by simply specifying the file name in the connect function.

import sqlite3

# Connect to an existing database
conn = sqlite3.connect('mydatabase.db')

In the above code, we connect to an existing database named ‘mydatabase.db’. If the file doesn’t exist, an error will be raised.

Conclusion

In this blog post, we learned how to create and connect to an SQLite database in Python. We also saw how to create tables and execute SQL commands. SQLite is a powerful and easy-to-use database solution for small to medium-sized applications. It provides a convenient way to store and retrieve data without the complexity of a full-fledged database management system.

I hope this tutorial was helpful. Happy coding!