Using PostgreSQL with Python
Learn how to use PostgreSQL with Python to store and retrieve data.
Introduction to PostgreSQL
PostgreSQL is a powerful, open-source database management system that allows you to store and manage data in a structured way. To get started with PostgreSQL, you'll need to install the psycopg2 package in Python. You can do this by running pip install psycopg2 in your terminal.
Connecting to PostgreSQL
To connect to a PostgreSQL database, you can use the following code:
import psycopg2
conn = psycopg2.connect(
dbname='database',
user='username',
password='password',
host='localhost'
)
This will connect to a PostgreSQL database running on the local machine.
Creating a Table
Once you have a connection to the database, you can create a table to store data. Here's an example:
cur = conn.cursor()
cur.execute('''CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT, email TEXT)''')
This will create a new table called users with three columns: id, name, and email.
Inserting Data
To insert data into the table, you can use the INSERT INTO statement. Here's an example:
cur.execute("""INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')""")
conn.commit()
This will insert a new row into the users table with the name John Doe and email john@example.com.