Connect to YugabyteDB using Python with psycopg2 and asyncio support
The Python ecosystem provides multiple drivers for connecting to YugabyteDB. The most commonly used driver is Psycopg2, which is fully compatible with YugabyteDB’s PostgreSQL-compatible YSQL API.
For production deployments, build psycopg2 from source for optimal performance. The psycopg2-binary package is recommended for development and testing only.
import psycopg2# Automatic connection managementwith psycopg2.connect( host='localhost', port=5433, dbname='yugabyte', user='yugabyte', password='yugabyte') as conn: with conn.cursor() as cursor: cursor.execute( 'SELECT name, age FROM users WHERE id = %s', (user_id,) ) result = cursor.fetchone() print(f'User: {result}')
# Fetch onecursor.execute('SELECT * FROM users WHERE id = %s', (1,))user = cursor.fetchone()print(f'User: {user}')# Fetch manycursor.execute('SELECT * FROM users WHERE age > %s', (25,))users = cursor.fetchmany(size=10)# Fetch allcursor.execute('SELECT * FROM users')all_users = cursor.fetchall()# Iterate over resultscursor.execute('SELECT name, email FROM users')for name, email in cursor: print(f'{name}: {email}')
# Update single recordcursor.execute( "UPDATE users SET age = %s WHERE id = %s", (31, 1))# Update multiple recordscursor.execute( "UPDATE users SET status = %s WHERE age > %s", ('senior', 50))print(f'Updated {cursor.rowcount} rows')conn.commit()
# Delete specific recordcursor.execute('DELETE FROM users WHERE id = %s', (1,))# Delete with conditioncursor.execute('DELETE FROM users WHERE age < %s', (18,))print(f'Deleted {cursor.rowcount} rows')conn.commit()
Always use parameterized queries to prevent SQL injection:
# ✅ Good - Parameterized querycursor.execute( 'SELECT * FROM users WHERE email = %s', (user_email,))# ❌ Bad - String interpolation (vulnerable to SQL injection)cursor.execute( f'SELECT * FROM users WHERE email = \'{user_email}\'')