sqliteHow can I use SQLite with Python to create a database?
Using SQLite with Python is a great way to create a database. SQLite is a lightweight database that is easy to set up and use. Here is an example of how to create a database using Python and SQLite:
import sqlite3
# Create a connection to the database
conn = sqlite3.connect("mydatabase.db")
# Create a cursor object
cursor = conn.cursor()
# Execute a query
cursor.execute("CREATE TABLE IF NOT EXISTS books (title TEXT, author TEXT, year INTEGER)")
# Commit the changes
conn.commit()
# Close the connection
conn.close()
This code will create a database called mydatabase.db with a table called books. The table will have three columns: title, author, and year.
Here is a breakdown of the code:
import sqlite3: imports the SQLite library into Python.conn = sqlite3.connect("mydatabase.db"): creates a connection to the database.cursor = conn.cursor(): creates a cursor object that will be used to execute queries.cursor.execute("CREATE TABLE IF NOT EXISTS books (title TEXT, author TEXT, year INTEGER)"): executes a query to create a table calledbookswith three columns:title,author, andyear.conn.commit(): commits the changes to the database.conn.close(): closes the connection to the database.
For more information on using SQLite with Python, check out the SQLite3 documentation.
More of Sqlite
- How do I use UUIDs in SQLite?
- How do I use SQLite with Visual Studio?
- How can I use an upsert statement to update data in a SQLite database?
- How do I install and use SQLite on Ubuntu?
- How can I use SQLite with Xamarin Forms?
- How do I use the SQLite sequence feature?
- How can I use SQLite with Xamarin Forms and C#?
- How do I use SQLite VACUUM to reclaim disk space?
- How do I use SQLite REPLACE to update existing records in a database?
- How do I use query parameters with SQLite?
See more codes...