title | description | ms.service | ms.subservice | ms.topic | ms.author | author | ms.devlang | ms.custom | ms.date |
---|---|---|---|---|---|---|---|---|---|
Quickstart: Connect using Python |
This quickstart provides several Python code samples you can use to connect and query data from Azure Database for PostgreSQL - Flexible Server. |
postgresql |
flexible-server |
quickstart |
sunila |
sunilagarwal |
python |
mvc, mode-api, devx-track-python |
03/16/2024 |
[!INCLUDE applies-to-postgresql-flexible-server]
In this quickstart, you connect to an Azure Database for PostgreSQL flexible server instance by using Python. You then use SQL statements to query, insert, update, and delete data in the database from Mac, Ubuntu Linux, and Windows platforms.
This article assumes that you're familiar with developing using Python, but you're new to working with Azure Database for PostgreSQL flexible server.
- An Azure account with an active subscription. Create an account for free.
- An Azure Database for PostgreSQL flexible server instance. To create Azure Database for PostgreSQL flexible server instance, refer to Create an Azure Database for PostgreSQL - Flexible Server instance using Azure portal.
- Python 2.7 or 3.6+.
- Latest pip package installer.
- If you created your Azure Database for PostgreSQL flexible server instance with Private access (VNet Integration), you will need to connect to your server from a resource within the same VNet as your server. You can create a virtual machine and add it to the VNet created with your Azure Database for PostgreSQL flexible server instance. Refer to Create and manage Azure Database for PostgreSQL - Flexible Server virtual network using Azure CLI.
- If you created your Azure Database for PostgreSQL flexible server instance with Public access (allowed IP addresses), you can add your local IP address to the list of firewall rules on your server. Refer to Create and manage Azure Database for PostgreSQL - Flexible Server firewall rules using the Azure CLI.
The psycopg2 module enables connecting to and querying a PostgreSQL database, and is available as a Linux, macOS, or Windows wheel package. Install the binary version of the module, including all the dependencies.
To install psycopg2
, open a terminal or command prompt and run the command pip install psycopg2
.
Connecting to an Azure Database for PostgreSQL flexible server instance requires the fully qualified server name and login credentials. You can get this information from the Azure portal.
-
In the Azure portal, search for and select your Azure Database for PostgreSQL flexible server name.
-
On the server's Overview page, copy the fully qualified Server name and the Admin username. The fully qualified Server name is always of the form <my-server-name>.postgres.database.azure.com.
You also need your admin password. If you forget it, you can reset it from overview page.
For each code example in this article:
-
Create a new file in a text editor.
-
Add the code example to the file. In the code, replace:
<server-name>
and<admin-username>
with the values you copied from the Azure portal.<admin-password>
with your server password.<database-name>
with the name of your Azure Database for PostgreSQL flexible server database. A default database named postgres was automatically created when you created your server. You can rename that database or create a new database by using SQL commands.
-
Save the file in your project folder with a .py extension, such as postgres-insert.py. For Windows, make sure UTF-8 encoding is selected when you save the file.
-
To run the file, change to your project folder in a command-line interface, and type
python
followed by the filename, for examplepython postgres-insert.py
.
The following code example connects to your Azure Database for PostgreSQL flexible server database using the psycopg2.connect function, and loads data with a SQL INSERT statement. The cursor.execute function executes the SQL query against the database.
import psycopg2
# Update connection string information
host = "<server-name>"
dbname = "<database-name>"
user = "<admin-username>"
password = "<admin-password>"
sslmode = "require"
# Construct connection string
conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password, sslmode)
conn = psycopg2.connect(conn_string)
print("Connection established")
cursor = conn.cursor()
# Drop previous table of same name if one exists
cursor.execute("DROP TABLE IF EXISTS inventory;")
print("Finished dropping table (if existed)")
# Create a table
cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
print("Finished creating table")
# Insert some data into the table
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150))
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("orange", 154))
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("apple", 100))
print("Inserted 3 rows of data")
# Clean up
conn.commit()
cursor.close()
conn.close()
When the code runs successfully, it produces the following output:
The following code example connects to your Azure Database for PostgreSQL flexible server database and uses cursor.execute with the SQL SELECT statement to read data. This function accepts a query and returns a result set to iterate over by using cursor.fetchall()
import psycopg2
# Update connection string information
host = "<server-name>"
dbname = "<database-name>"
user = "<admin-username>"
password = "<admin-password>"
sslmode = "require"
# Construct connection string
conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password, sslmode)
conn = psycopg2.connect(conn_string)
print("Connection established")
cursor = conn.cursor()
# Fetch all rows from table
cursor.execute("SELECT * FROM inventory;")
rows = cursor.fetchall()
# Print all rows
for row in rows:
print("Data row = (%s, %s, %s)" %(str(row[0]), str(row[1]), str(row[2])))
# Cleanup
conn.commit()
cursor.close()
conn.close()
The following code example connects to your Azure Database for PostgreSQL flexible server database and uses cursor.execute with the SQL UPDATE statement to update data.
import psycopg2
# Update connection string information
host = "<server-name>"
dbname = "<database-name>"
user = "<admin-username>"
password = "<admin-password>"
sslmode = "require"
# Construct connection string
conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password, sslmode)
conn = psycopg2.connect(conn_string)
print("Connection established")
cursor = conn.cursor()
# Update a data row in the table
cursor.execute("UPDATE inventory SET quantity = %s WHERE name = %s;", (200, "banana"))
print("Updated 1 row of data")
# Cleanup
conn.commit()
cursor.close()
conn.close()
The following code example connects to your Azure Database for PostgreSQL flexible server database and uses cursor.execute with the SQL DELETE statement to delete an inventory item that you previously inserted.
import psycopg2
# Update connection string information
host = "<server-name>"
dbname = "<database-name>"
user = "<admin-username>"
password = "<admin-password>"
sslmode = "require"
# Construct connection string
conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password, sslmode)
conn = psycopg2.connect(conn_string)
print("Connection established")
cursor = conn.cursor()
# Delete data row from table
cursor.execute("DELETE FROM inventory WHERE name = %s;", ("orange",))
print("Deleted 1 row of data")
# Cleanup
conn.commit()
cursor.close()
conn.close()
[!div class="nextstepaction"] Migrate your database using dump and restore