Python drivers
The Yugabyte Psycopg2 smart driver is a distributed Python driver for YSQL, built on the PostgreSQL psycopg2 driver. Although the upstream PostgreSQL psycopg2 driver works with YugabyteDB, the Yugabyte driver is cluster- and topology-aware, and eliminates the need for external load balancers.
CRUD operations with YugabyteDB Psycopg2 driver
Learn how to establish a connection to YugabyteDB database and begin basic CRUD operations using the steps in the Build an application page under the Quick start section.
The following sections break down the quick start example to demonstrate how to perform common tasks required for Python application development using the YugabyteDB Psycopg2 driver.
After completing these steps, you should have a working Python application that uses Psycopg2 to connect to your cluster, set up tables, run queries, and print out results.
Step 1: Add the YugabyteDB driver dependency
Step 2: Connect to your cluster
Python applications can connect to and query the YugabyteDB database. First, import the psycopg2 package.
import psycopg2
The Connection details can be provided as a string or a dictionary.
-
Connection String
"dbname=database_name host=hostname port=port user=username password=password load_balance=true" -
Connection Dictionary
user = 'username', password='xxx', host = 'hostname', port = 'port', dbname = 'database_name', load_balance='True'
Example URL for connecting to YugabyteDB can be seen below.
conn = psycopg2.connect(dbname='yugabyte',host='localhost',port='5433',user='yugabyte',password='yugabyte', load_balance='True')
| Parameter | Description | Default |
|---|---|---|
| host | Hostname of the YugabyteDB instance | localhost |
| port | Listen port for YSQL | 5433 |
| database/dbname | Database name | yugabyte |
| user | User connecting to the database | yugabyte |
| password | User password | yugabyte |
| load-balance | enables uniform load balancing | false |
Use SSL
Use the following example URL for connecting to a YugabyteDB cluster with SSL enabled:
conn = psycopg2.connect("host=<hostname> port=5433 dbname=yugabyte user=<username> password=<password> load_balance=true sslmode=verify-full sslrootcert=/Users/my-user/Downloads/root.crt")
| Parameter | Description | Default |
|---|---|---|
| sslmode | SSL mode | prefer |
| sslrootcert | path to the root certificate on your computer | ~/.postgresql/ |
If you have created a cluster on YugabyteDB Managed, follow the steps to obtain the cluster connection parameters and SSL Root certificate.
Step 3: Query the YugabyteDB cluster from your application
-
Create a new Python file called
QuickStartApp.pyin the base package directory of your project. -
Copy the following sample code to set up tables and query the table contents. Replace the connection string
yburlwith the cluster credentials and SSL certificate, if required.
import psycopg2
# Create the database connection.
yburl = "host=127.0.0.1 port=5433 dbname=yugabyte user=yugabyte password=yugabyte load_balance=True"
conn = psycopg2.connect(yburl)
# Open a cursor to perform database operations.
# The default mode for psycopg2 is "autocommit=false".
conn.set_session(autocommit=True)
cur = conn.cursor()
# Create the table. (It might preexist.)
cur.execute(
"""
DROP TABLE IF EXISTS employee
""")
cur.execute(
"""
CREATE TABLE employee (id int PRIMARY KEY,
name varchar,
age int,
language varchar)
""")
print("Created table employee")
cur.close()
# Take advantage of ordinary, transactional behavior for DMLs.
conn.set_session(autocommit=False)
cur = conn.cursor()
# Insert a row.
cur.execute("INSERT INTO employee (id, name, age, language) VALUES (%s, %s, %s, %s)",
(1, 'John', 35, 'Python'))
print("Inserted (id, name, age, language) = (1, 'John', 35, 'Python')")
# Query the row.
cur.execute("SELECT name, age, language FROM employee WHERE id = 1")
row = cur.fetchone()
print("Query returned: %s, %s, %s" % (row[0], row[1], row[2]))
# Commit and close down.
conn.commit()
cur.close()
conn.close()
When you run the QuickStartApp.py project, you should see output similar to the following:
Created table employee
Inserted (id, name, age, language) = (1, 'John', 35, 'Python')
Query returned: John, 35, Python
If there is no output or you get an error, verify the parameters included in the connection string.
Next steps
- Learn how to build Python applications using Django
- Learn how to build Python applications using SQLAlchemy
- Learn more about fundamentals of the YugabyteDB Psycopg2 Driver