Build a Python application

The following tutorial creates a simple Python application that connects to a YugabyteDB cluster using the psycopg database adapter, performs a few basic database operations — creating a table, inserting data, and running a SQL query — and prints the results to the screen.

Before you begin

This tutorial assumes that you have satisfied the following prerequisites.

YugabyteDB

YugabyteDB is up and running. If you are new to YugabyteDB, you can have YugabyteDB up and running within five minutes by following the steps in Quick start.

Python

Python 3, or later, is installed.

Psycopg database adapter

Psycopg,the popular PostgreSQL database adapter for Python, is installed. To install a binary version of psycopg2, run the following pip3 command.

  1. $ pip3 install psycopg2-binary

For details about using this database adapter, see the Psycopg documentation.

Create the Python application

Create a file yb-sql-helloworld.py and add the following content to it.

  1. import psycopg2
  2. # Create the database connection.
  3. conn = psycopg2.connect("host=127.0.0.1 port=5433 dbname=yugabyte user=yugabyte password=yugabyte")
  4. # Open a cursor to perform database operations.
  5. # The default mode for psycopg2 is "autocommit=false".
  6. conn.set_session(autocommit=True)
  7. cur = conn.cursor()
  8. # Create the table. (It might preexist.)
  9. cur.execute(
  10. """
  11. DROP TABLE IF EXISTS employee
  12. """)
  13. cur.execute(
  14. """
  15. CREATE TABLE employee (id int PRIMARY KEY,
  16. name varchar,
  17. age int,
  18. language varchar)
  19. """)
  20. print("Created table employee")
  21. cur.close()
  22. # Take advantage of ordinary, transactional behavior for DMLs.
  23. conn.set_session(autocommit=False)
  24. cur = conn.cursor()
  25. # Insert a row.
  26. cur.execute("INSERT INTO employee (id, name, age, language) VALUES (%s, %s, %s, %s)",
  27. (1, 'John', 35, 'Python'))
  28. print("Inserted (id, name, age, language) = (1, 'John', 35, 'Python')")
  29. # Query the row.
  30. cur.execute("SELECT name, age, language FROM employee WHERE id = 1")
  31. row = cur.fetchone()
  32. print("Query returned: %s, %s, %s" % (row[0], row[1], row[2]))
  33. # Commit and close down.
  34. conn.commit()
  35. cur.close()
  36. conn.close()

Run the application

To run the application, run the following Python script you just created.

  1. $ python yb-sql-helloworld.py

You should see the following output.

  1. Created table employee
  2. Inserted (id, name, age, language) = (1, 'John', 35, 'Python')
  3. Query returned: John, 35, Python