Vous êtes sur la page 1sur 159

CCoonntteennttss

Azure DB for PostgreSQL Docs Overview Azure DB for PostgreSQL Quickstarts Create DB - Portal Create DB - Azure CLI Connect & query Python Node.js Java Ruby PHP .NET Go Tutorials 1 - Design a Database Azure portal Azure CLI 2 - Design Web App - Python Samples Azure CLI Concepts DB & Servers Servers Supported versions PostgreSQL extensions Server logs High availability Resources

Pricing tiers Limits Data access & security Firewall rules Configure SSL VNet Business continuity Overview Backup and restore Monitor Development Connection libraries How-to guides Create users Manage firewall Azure portal Azure CLI Restore a server Azure portal Azure CLI Migrate a database Dump & restore Import & export Minimal-downtime migration Configure server parameters Azure portal Azure CLI Access server logs Azure portal Azure CLI Monitor Create alerts on metrics

What is Azure Database for PostgreSQL?

6/15/2018 • 3 minutes to read • Edit Online

Azure Database for PostgreSQL is a relational database service in the Microsoft cloud built for developers based on the community version of open-source PostgreSQL database engine. Azure Database for PostgreSQL delivers:

Built-in high availability with no additional costdatabase engine. Azure Database for PostgreSQL delivers: Predictable performance, using inclusive pay-as-you-go

Predictable performance, using inclusive pay-as-you-go pricingdelivers: Built-in high availability with no additional cost Scale as needed within seconds Secured to protect

Scale as needed within secondsperformance, using inclusive pay-as-you-go pricing Secured to protect sensitive data at-rest and in-motion

Secured to protect sensitive data at-rest and in-motionpay-as-you-go pricing Scale as needed within seconds Automatic backups and point-in-time-restore for up to 35

Automatic backups and point-in-time-restore for up to 35 daysSecured to protect sensitive data at-rest and in-motion Enterprise-grade security and compliance All those

Enterprise-grade security and compliancebackups and point-in-time-restore for up to 35 days All those capabilities require almost no administration, and

All those capabilities require almost no administration, and all are provided at no additional cost. These capabilities allow you to focus on rapid application development and accelerating your time to market, rather than allocating precious time and resources to managing virtual machines and infrastructure. In addition, you can continue to develop your application with the open-source tools and platform of your choice, and deliver with the speed and efficiency your business demands without having to learn new skills.

This article is an introduction to Azure Database for PostgreSQL core concepts and features related to performance, scalability, and manageability. See these quickstarts to get you started:

Create an Azure Database for PostgreSQL using Azure portaland manageability. See these quickstarts to get you started: Create an Azure Database for PostgreSQL using

Create an Azure Database for PostgreSQL using the Azure CLICreate an Azure Database for PostgreSQL using Azure portal For a set of Azure CLI samples,

For a set of Azure CLI samples, see:

Azure CLI samples for Azure Database for PostgreSQLusing the Azure CLI For a set of Azure CLI samples, see: Adjust performance and scale

Adjust performance and scale within seconds

Azure Database for PostgreSQL service offers three pricing tiers: Basic, General Purpose, and Memory Optimized. Each tier offers different resource capabilities to support your database workloads. You can build your first app on a small database for a few dollars a month, and then adjust the scale to meet the needs of your solution. Dynamic scalability enables your database to transparently respond to rapidly changing resource requirements. You only pay for the resources you need, and only when you need them. See Pricing tiers for details.

Monitoring and alerting

How do you decide when to dial up or down? You use the built-in Azure monitoring and alerting features. Using these tools, you can quickly assess the impact of scaling up or down based on your current or projected performance or storage needs. See Alerts for details.

Keep your app and business running

Azure's industry leading 99.99% availability service level agreement (SL A), powered by a global network of Microsoft-managed datacenters, helps keep your app running 24/7. With every Azure Database for PostgreSQL server, you take advantage of built-in security, fault tolerance, and data protection that you would otherwise have to buy or design, build, and manage. With Azure Database for PostgreSQL, each pricing tier offers a comprehensive set of business continuity features and options that you can use to get up and running and stay that way. You can use point-in-time restore to return a database to an earlier state, as far back as 35 days. In

addition, if the datacenter hosting your databases experiences an outage, you can restore databases from geo- redundant copies of recent backups.

Secure your data

The Azure Database for PostgreSQL service uses storage encryption for data at-rest. Data, including backups, is encrypted on disk (with the exception of temporary files created by the engine while running queries). The service uses AES 256-bit cipher that is included in Azure storage encryption, and the keys are system managed. Storage encryption is always on and cannot be disabled.

By default, the Azure Database for PostgreSQL service is configured to require SSL connection security for data in-motion across the network. Enforcing SSL connections between your database server and your client applications helps protect against "man in the middle" attacks by encrypting the data stream between the server and your application. Optionally, you can disable requiring SSL for connecting to your database service if your client application does not support SSL connectivity.

Contacts

For any questions or suggestions you might have about working with Azure Database for PostgreSQL, send an email to the Azure Database for PostgreSQL Team (@Ask Azure DB for PostgreSQL). Note that this is not a technical support alias.

In addition, consider the following points of contact as appropriate:

To contact Azure Support, file a ticket from the Azure portal . file a ticket from the Azure portal.

To fix an issue with your account, file a support request in the Azure portal. support request in the Azure portal.

To provide feedback or to request new features, create an entry via UserVoice . UserVoice.

Next steps

See the pricing page for cost comparisons and calculators. pricing page for cost comparisons and calculators.

Get started by creating your first Azure Database for PostgreSQL . creating your first Azure Database for PostgreSQL.

Build your first app in Python, PHP, Ruby, C#, Java, Node.js: Connection libraries Connection libraries

Quickstart: Create an Azure Database for PostgreSQL server in the Azure portal

5/23/2018 • 11 minutes to read • Edit Online

Azure Database for PostgreSQL is a managed service that you use to run, manage, and scale highly available PostgreSQL databases in the cloud. This Quickstart shows you how to create an Azure Database for PostgreSQL server in about five minutes using the Azure portal.

If you don't have an Azure subscription, create a free Azure account before you begin.

Sign in to the Azure portal

Open your web browser and go to the portal. Enter your credentials to sign in to the portal. The default view is your service dashboard.

Create an Azure Database for PostgreSQL server

An Azure Database for PostgreSQL server is created with a configured set of compute and storage resources. The server is created within an Azure resource group.

To create an Azure Database for PostgreSQL server, take the following steps:

1. Select the Create a resource button (+) in the upper-left corner of the portal.

2. Select Databases > Azure Database for PostgreSQL.

2. Select Databases > Azure Database for PostgreSQL . 3. Fill out the new server details
SETTING SUGGESTED VALUE DESCRIPTION Server name mydemoserver A unique name that identifies your Azure

SETTING

SUGGESTED VALUE

DESCRIPTION

Server name

mydemoserver

A unique name that identifies your Azure Database for PostgreSQL server. The domain name postgres.database.azure.com is appended to the server name you provide. The server can contain only lowercase letters, numbers, and the hyphen (-) character. It must contain at least 3 through 63 characters.

Subscription

Your subscription name

The Azure subscription that you want to use for your server. If you have multiple subscriptions, choose the subscription in which you're billed for the resource.

Resource group

myresourcegroup

A new resource group name or an existing one from your subscription.

SETTING

SUGGESTED VALUE

DESCRIPTION

Select source

Blank

Select Blank to create a new server from scratch. (You would select Backup if you were creating a server from a geo-backup of an existing Azure Database for PostgreSQL server).

Server admin login

myadmin

Your own login account to use when you connect to the server. The admin login name can't be azure_superuser, azure_pg_admin, admin, administrator, root, guest, or public. It can't start with pg

Password

Your password

A new password for the server admin account. It must contain between 8 and 128 characters. Your password must contain characters from three of the following categories: English uppercase letters, English lowercase letters, numbers (0 through 9), and non-alphanumeric characters (!, $, #, %, etc.).

Location

The region closest to your users

The location that is closest to your users.

Version

The latest version

The latest PostgreSQL version, unless you have specific requirements otherwise.

Pricing tier

General Purpose, Gen 4, 2 vCores, 5 GB, 7 days, Geographically Redundant

The compute, storage, and backup configurations for your new server. Select Pricing tier. Next, select the General Purpose tab. Gen 4, 2 vCores, 5 GB, and 7 days are the default values for Compute Generation, vCore, Storage, and Backup Retention Period. You can leave those sliders as is. To enable your server backups in geo- redundant storage select Geographically Redundant from the Backup Redundancy Options. To save this pricing tier selection, select OK. The next screenshot captures these selections.

IIMMPPOORRTTAANNTT The server admin login and password that you specify here are required to sign in to the server and its databases later in this Quickstart. Remember or record this information for later use.

4. Select Create to provision the server. This operation may take a few minutes. 5.

4. Select Create to provision the server. This operation may take a few minutes.

5. On the toolbar, select the Notifications icon (a bell) to monitor the deployment process. Once the deployment is done, you can select Pin to dashboard, which creates a tile for this server on your Azure portal dashboard as a shortcut to the server's Overview page. Selecting Go to resource opens the server's Overview page.

Go to resource opens the server's Overview page. By default, a postgres database is created under

By default, a postgres database is created under your server. The postgres database is a default database that's meant for use by users, utilities, and third-party applications. (The other default database is azure_maintenance. Its function is to separate the managed service processes from user actions. You cannot access this database.)

Configure a server-level firewall rule

Azure Database for PostgreSQL creates a firewall at the server level. It prevents external applications and tools from connecting to the server and any databases on the server, unless you create a rule to open the firewall for specific IP addresses.

2. On the server page, select Connection security . 3. Under the Firewall rules ,

2. On the server page, select Connection security.

3. Under the Firewall rules, in the Rule Name column, select the blank text box to begin creating the firewall rule.

For this Quickstart, let's allow all IP addresses into the server. Fill in the text box in each column with the following values:

RULE NAME

START IP

END IP

AllowAllIps

0.0.0.0

255.255.255.255

NAME START IP END IP AllowAllIps 0.0.0.0 255.255.255.255 4. On the upper toolbar of the Connection

4. On the upper toolbar of the Connection security page, select Save. Wait until the notification appears stating that the connection security update has finished successfully before you continue.

NNOOTTEE Connections to your Azure Database for PostgreSQL server communicate over port 5432. When you try to connect from within a corporate network, outbound traffic over port 5432 might not be allowed by your network's firewall. If so, you can't connect to your server unless your IT department opens port 5432.

Get the connection information

When you create your Azure Database for PostgreSQL server, a default database named postgres is created. To connect to your database server, you need your full server name and admin login credentials. You might have noted those values earlier in the Quickstart article. If you didn't, you can easily find the server name and login information on the server Overview page in the portal.

Open your server's Overview page. Make a note of the Server name and the Server admin login name. Hover your cursor over each field, and the copy symbol appears to the right of the text. Select the copy symbol as needed to copy the values.

text. Select the copy symbol as needed to copy the values. Connect to the PostgreSQL Database

Connect to the PostgreSQL Database by using psql in Cloud Shell

There are a number of applications you can use to connect to your Azure Database for PostgreSQL server. Let's first use the psql command-line utility to illustrate how to connect to the server. You can use a web browser and Azure Cloud Shell as described here without the need to install any additional software. If you have the psql utility installed locally on your own machine, you can connect from there as well.

1. In the top navigation pane, select the terminal symbol to open Cloud Shell.

pane, select the terminal symbol to open Cloud Shell. 2. Cloud Shell opens in your browser,

2. Cloud Shell opens in your browser, where you can type Bash shell commands.

in your browser, where you can type Bash shell commands. 3. At the Cloud Shell prompt,

3. At the Cloud Shell prompt, connect to a database in your Azure Database for PostgreSQL server by typing the psql command line.

To connect to an Azure Database for PostgreSQL server with the psql utility, use the following format:

psql --host=<yourserver> --port=<port> --username=<server admin login> --dbname=<database name>

For example, the following command connects to an example server:

psql --host=mydemoserver.postgres.database.azure.com --port=5432 --username=myadmin@mydemoserver -- dbname=postgres

PSQL PARAMETER

VALUE

DESCRIPTION

--host

Server name

The server name value that you used when you created the Azure Database for PostgreSQL server earlier. The example server shown is mydemoserver.postgres.databas e.azure.com. Use the fully qualified domain name (*.postgres.database.azure.com) as shown in the example. If you don't remember your server name, follow the steps in the previous section to get the connection information.

--port

5432

The port to use when you connect to the Azure Database for PostgreSQL server.

--username

Server admin login name

The server admin login username that you supplied when you created the Azure Database for PostgreSQL server earlier. If you don't remember your username, follow the steps in the previous section to get the connection information. The format is username@servername.

--dbname

postgres

The default, system-generated database name that was created for the first connection. Later, you create your own database.

After you run the psql command with your own parameter values, you're prompted to enter the server admin password. This password is the same one that you provided when you created the server.

PSQL PARAMETER

SUGGESTED VALUE

DESCRIPTION

password

Your admin password

The typed password characters aren't shown on the bash prompt. After you type all the characters, hit the Enter key to authenticate and connect.

After you connect, the psql utility displays a postgres prompt where you type sql commands. In the initial connection output, a warning may appear because the psql in Cloud Shell might be a different version than the Azure Database for PostgreSQL server version.

Example psql output:

psql (9.5.7, server 9.6.2) WARNING: psql major version 9.5, server major version 9.6. Some psql features might not work. SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-SHA384, bits: 256, compression: off) Type "help" for help.

postgres=>

TTIIPP If the firewall is not configured to allow the IP address of Cloud Shell, the following error occurs:

"psql: FATAL: no pg_hba.conf entry for host "0.0.0.0", user "myadmin", database "postgres", SSL on FATAL: SSL connection is required. Specify SSL options and retry.

To resolve the error, make sure the server configuration matches the steps in the "Configure a server-level firewall rule" section of this article.

4. Create a blank database called "mypgsqldb" at the prompt by typing the following command:

CREATE DATABASE mypgsqldb;

The command might take a few minutes to finish.

5. At the prompt, execute the following command to switch connections to the newly created database mypgsqldb:

\c mypgsqldb

6. Type

You connected to the Azure Database for PostgreSQL server via psql in Cloud Shell, and you created a blank user database. Continue to the next section to connect by using another common tool, pgAdmin.

\q
\q

, and then select the Enter key to quit psql. You can close Cloud Shell after you're finished.

Connect to the PostgreSQL Server using pgAdmin

pgAdmin is an open-source tool used with PostgreSQL. You can install pgAdmin from the pgAdmin website. The pgAdmin version you're using may be different from what is used in this Quickstart. Read the pgAdmin documentation if you need additional guidance.

1. Open the pgAdmin application on your client computer.

2. From the toolbar go to Object, hover over Create, and select Server.

3. In the Create - Server dialog box, on the General tab, enter a unique friendly name for the server, such as mydemoserver.

4. In the Create - Server dialog box, on the Connection tab, fill in the

4. In the Create - Server dialog box, on the Connection tab, fill in the settings table.

box, on the Connection tab, fill in the settings table. PGADMIN PARAMETER VALUE DESCRIPTION Host

PGADMIN PARAMETER

VALUE

DESCRIPTION

Host name/address

Server name

The server name value that you used when you created the Azure Database for PostgreSQL server earlier. Our example server is mydemoserver.postgres.databas e.azure.com. Use the fully qualified domain name (*.postgres.database.azure.com) as shown in the example. If you don't remember your server name, follow the steps in the previous section to get the connection information.

Port

5432

The port to use when you connect to the Azure Database for PostgreSQL server.

Maintenance database

postgres

The default system-generated database name.

PGADMIN PARAMETER

VALUE

DESCRIPTION

Username

Server admin login name

The server admin login username that you supplied when you created the Azure Database for PostgreSQL server earlier. If you don't remember the username, follow the steps in the previous section to get the connection information. The format is username@servername.

Password

Your admin password

The password you chose when you created the server earlier in this Quickstart.

Role

Leave blank

There's no need to provide a role name at this point. Leave the field blank.

SSL mode

Require

You can set the SSL mode in pgAdmin's SSL tab. By default, all Azure Database for PostgreSQL servers are created with SSL enforcing turned on. To turn off SSL enforcing, see SSL Enforcing.

5.

Select Save.

6.

In the Browser pane on the left, expand the Servers node. Select your server, for example, mydemoserver. Click to connect to it.

7.

Expand the server node, and then expand Databases under it. The list should include your existing postgres database and any other databases you've created. You can create multiple databases per server with Azure Database for PostgreSQL.

8.

Right-click Databases, choose the Create menu, and then select Database.

9.

Type a database name of your choice in the Database field, such as mypgsqldb2.

10.

Select the Owner for the database from the list box. Choose your server admin login name, such as the example, my admin.

Choose your server admin login name, such as the example, my admin . 11. Select Save

12.

In the Browser pane, you can see the database that you created in the list of databases under your server name.

Clean up resources

TTIIPP Other Quickstarts in this collection build on this Quickstart. If you plan to continue working with Quickstarts, don't clean up the resources that you created in this Quickstart. If you don't plan to continue, follow these steps to delete the resources that were created by this Quickstart in the portal.

To delete the entire resource group, including the newly created server:

1. Locate your resource group in the portal. On the menu on the left, select Resource groups. Then select the name of your resource group, such as the example, myresourcegroup.

2. On your resource group page, select Delete. Type the name of your resource group, such as the example, myresourcegroup, in the text box to confirm deletion. Select Delete.

To delete only the newly created server:

1. Locate your server in the portal, if you don't have it open. On the menu on the left, select All resources. Then search for the server you created.

2. On the Overview page, select Delete.

you created. 2. On the Overview page, select Delete . 3. Confirm the name of the

3. Confirm the name of the server you want to delete, and view the databases under it that are affected. Type your server name in the text box, such as the example, mydemoserver. Select Delete.

Next steps

Migrate your database using Export and Import

Quickstart: Create an Azure Database for PostgreSQL using the Azure CLI

6/27/2018 • 7 minutes to read • Edit Online

Azure Database for PostgreSQL is a managed service that enables you to run, manage, and scale highly available PostgreSQL databases in the cloud. The Azure CLI is used to create and manage Azure resources from the command line or in scripts. This quickstart shows you how to create an Azure Database for PostgreSQL server in an Azure resource group using the Azure CLI.

If you don't have an Azure subscription, create a free account before you begin.

Open Azure Cloud Shell

Azure Cloud Shell is a free, interactive shell that you can use to run the steps in this article. Common Azure tools are preinstalled and configured in Cloud Shell for you to use with your account. Just select the Copy button to copy the code, paste it in Cloud Shell, and then press Enter to run it. There are a few ways to open Cloud Shell:

Select Try It in the upper-right corner of a code block.

Select Try It in the upper-right corner of a code block. Open Cloud Shell in your

Open Cloud Shell in your browser.

corner of a code block. Open Cloud Shell in your browser. Select the Cloud Shell button

Select the Cloud Shell button on the menu in the upper- right corner of the Azure portal.

the menu in the upper- right corner of the Azure portal . If you choose to

If you choose to install and use the CLI locally, this article requires that you are running the Azure CLI version 2.0

If you are running the CLI locally, you need to log in to your account using the az login command. Note the id property from the command output for the corresponding subscription name.

az login

If you have multiple subscriptions, choose the appropriate subscription in which the resource should be billed. Select the specific subscription ID under your account using az account set command. Substitute the id property from the az login output for your subscription into the subscription id placeholder.

az account set --subscription <subscription id>

Create a resource group

Create an Azure resource group using the az group create command. A resource group is a logical container into which Azure resources are deployed and managed as a group. You should provide a unique name. The following

example creates a resource group named

myresourcegroup

in the

westus
westus

location.

az group create --name myresourcegroup --location westus

Create an Azure Database for PostgreSQL server

Create an Azure Database for PostgreSQL server using the az postgres server create command. A server contains a group of databases managed as a group.

The following example creates a server in West US named

mydemoserver

in your resource group

myresourcegroup

with server admin login

myadmin
myadmin

. This is a Gen 4 General Purpose server with 2 vCores. The

name of a server maps to DNS name and is thus required to be globally unique in Azure. Substitute the

<server_admin_password>

with your own value.

az postgres server create --resource-group myresourcegroup --name mydemoserver --location westus --admin- user myadmin --admin-password <server_admin_password> --sku-name GP_Gen4_2 --version 9.6

The sku-name parameter value follows the convention {pricing tier}_{compute generation}_{vCores} as in the examples below:

generation}_{vCores} as in the examples below: --sku-name B_Gen4_4 maps to Basic, Gen 4, and 4 vCores.

--sku-name B_Gen4_4generation}_{vCores} as in the examples below: maps to Basic, Gen 4, and 4 vCores. --sku-name GP_Gen5_32

maps to Basic, Gen 4, and 4 vCores.

--sku-name B_Gen4_4 maps to Basic, Gen 4, and 4 vCores. --sku-name GP_Gen5_32 --sku-name MO_Gen5_2 maps to

--sku-name GP_Gen5_32--sku-name B_Gen4_4 maps to Basic, Gen 4, and 4 vCores. --sku-name MO_Gen5_2 maps to General Purpose,

maps to Basic, Gen 4, and 4 vCores. --sku-name GP_Gen5_32 --sku-name MO_Gen5_2 maps to General Purpose,

--sku-name MO_Gen5_2maps to Basic, Gen 4, and 4 vCores. --sku-name GP_Gen5_32 maps to General Purpose, Gen 5,

maps to General Purpose, Gen 5, and 32 vCores.

maps to Memory Optimized, Gen 5, and 2 vCores.

Please see the pricing tiers documentation to understand the valid values per region and per tier.

IIMMPPOORRTTAANNTT The server admin login and password that you specify here are required to log in to the server and its databases later in this quickstart. Remember or record this information for later use.

By default, postgres database gets created under your server. The postgres database is a default database meant for use by users, utilities, and third-party applications.

Configure a server-level firewall rule

Create an Azure PostgreSQL server-level firewall rule with the az postgres server firewall-rule create command. A server-level firewall rule allows an external application, such as psql or PgAdmin to connect to your server through the Azure PostgreSQL service firewall.

You can set a firewall rule that covers an IP range to be able to connect from your network. The following

example uses az postgres server firewall-rule create to create a firewall rule

AllowMyIP
AllowMyIP

for a single IP address.

az postgres server firewall-rule create --resource-group myresourcegroup --server mydemoserver --name AllowMyIP --start-ip-address 192.168.0.1 --end-ip-address 192.168.0.1

NNOOTTEE Azure PostgreSQL server communicates over port 5432. When connecting from within a corporate network, outbound traffic over port 5432 may not be allowed by your network's firewall. Have your IT department open port 5432 to connect to your Azure PostgreSQL server.

Get the connection information

To connect to your server, you need to provide host information and access credentials.

az postgres server show --resource-group myresourcegroup --name mydemoserver

The result is in JSON format. Make a note of the administratorLogin and fullyQualifiedDomainName.

{

"administratorLogin": "myadmin", "earliestRestoreDate": null, "fullyQualifiedDomainName": "mydemoserver.postgres.database.azure.com", "id": "/subscriptions/00000000-0000-0000-0000-

000000000000/resourceGroups/myresourcegroup/providers/Microsoft.DBforPostgreSQL/servers/mydemoserver",

"location": "westus", "name": "mydemoserver", "resourceGroup": "myresourcegroup", "sku": { "capacity": 2, "family": "Gen4", "name": "GP_Gen4_2", "size": null, "tier": "GeneralPurpose"

}, "sslEnforcement": "Enabled", "storageProfile": { "backupRetentionDays": 7, "geoRedundantBackup": "Disabled", "storageMb": 5120

}, "tags": null, "type": "Microsoft.DBforPostgreSQL/servers", "userVisibleState": "Ready", "version": "9.6"

}

Connect to PostgreSQL database using psql

If your client computer has PostgreSQL installed, you can use a local instance of psql to connect to an Azure PostgreSQL server. Let's now use the psql command-line utility to connect to the Azure PostgreSQL server.

1. Run the following psql command to connect to an Azure Database for PostgreSQL server

psql --host=<servername> --port=<port> --username=<user@servername> --dbname=<dbname>

For example, the following command connects to the default database called postgres on your PostgreSQL server mydemoserver.postgres.database.azure.com using access credentials. Enter the

<server_admin_password>

you chose when prompted for password.

psql --host=mydemoserver.postgres.database.azure.com --port=5432 --username=myadmin@mydemoserver -- dbname=postgres

2. Once you are connected to the server, create a blank database at the prompt.

mypgsqldb:

\c mypgsqldb

Connect to the PostgreSQL Server using pgAdmin

pgAdmin is an open-source tool used with PostgreSQL. You can install pgAdmin from the pgAdmin website. The pgAdmin version you're using may be different from what is used in this Quickstart. Read the pgAdmin documentation if you need additional guidance.

1. Open the pgAdmin application on your client computer.

2. From the toolbar go to Object, hover over Create, and select Server.

3. In the Create - Server dialog box, on the General tab, enter a unique friendly name for the server, such as mydemoserver.

unique friendly name for the server, such as mydemoserver . 4. In the Create - Server

4. In the Create - Server dialog box, on the Connection tab, fill in the settings table.

the Create - Server dialog box, on the Connection tab, fill in the settings table. PGADMIN

PGADMIN PARAMETER

VALUE

DESCRIPTION

PGADMIN PARAMETER

VALUE

DESCRIPTION

Host name/address

Server name

The server name value that you used when you created the Azure Database for PostgreSQL server earlier. Our example server is mydemoserver.postgres.databas e.azure.com. Use the fully qualified domain name (*.postgres.database.azure.com) as shown in the example. If you don't remember your server name, follow the steps in the previous section to get the connection information.

Port

5432

The port to use when you connect to the Azure Database for PostgreSQL server.

Maintenance database

postgres

The default system-generated database name.

Username

Server admin login name

The server admin login username that you supplied when you created the Azure Database for PostgreSQL server earlier. If you don't remember the username, follow the steps in the previous section to get the connection information. The format is username@servername.

Password

Your admin password

The password you chose when you created the server earlier in this Quickstart.

Role

Leave blank

There's no need to provide a role name at this point. Leave the field blank.

SSL mode

Require

You can set the SSL mode in pgAdmin's SSL tab. By default, all Azure Database for PostgreSQL servers are created with SSL enforcing turned on. To turn off SSL enforcing, see SSL Enforcing.

5. Select Save.

6. In the Browser pane on the left, expand the Servers node. Select your server, for example, mydemoserver. Click to connect to it.

7. Expand the server node, and then expand Databases under it. The list should include your existing postgres database and any other databases you've created. You can create multiple databases per server with Azure Database for PostgreSQL.

8. Right-click Databases, choose the Create menu, and then select Database.

10.

Select the Owner for the database from the list box. Choose your server admin login name, such as the example, my admin.

server admin login name, such as the example, my admin . 11. Select Save to create

11. Select Save to create a new blank database.

12. In the Browser pane, you can see the database that you created in the list of databases under your server name.

Clean up resources

Clean up all resources you created in the quickstart by deleting the Azure resource group.

TTIIPP Other quickstarts in this collection build upon this quickstart. If you plan to continue to work with subsequent quickstarts, do not clean up the resources created in this quickstart. If you do not plan to continue, use the following steps to delete all resources created by this quickstart in the Azure CLI.

az group delete --name myresourcegroup

If you would just like to delete the one newly created server, you can run az postgres server delete command.

az postgres server delete --resource-group myresourcegroup --name mydemoserver

Next steps

Migrate your database using Export and Import

Azure Database for PostgreSQL: Use Python to connect and query data

2/27/2018 • 5 minutes to read • Edit Online

This quickstart demonstrates how to use Python to connect to an Azure Database for PostgreSQL. It also demonstrates how to use SQL statements to query, insert, update, and delete data in the database from macOS, Ubuntu Linux, and Windows platforms. The steps in this article assume that you are familiar with developing using Python and are new to working with Azure Database for PostgreSQL.

Prerequisites

This quickstart uses the resources created in either of these guides as a starting point:

Create DB - Portalcreated in either of these guides as a starting point: Create DB - CLI You also

Create DB - CLIof these guides as a starting point: Create DB - Portal You also need: python installed

You also need:

python installed python installed

pip package installed (pip is already installed if you're working with Python 2 >=2.7.9 or pip package installed (pip is already installed if you're working with Python 2 >=2.7.9 or Python 3 >=3.4 binaries downloaded from python.org.

Install the Python connection libraries for PostgreSQL

Install the psycopg2 package, which enables you to connect and query the database. psycopg2 is available on PyPI in the form of wheel packages for the most common platforms (Linux, OSX, Windows). Use pip install to get the binary version of the module including all the dependencies.

1. On your own computer, launch a command-line interface:

On Linux, launch the Bash shell.

On Linux, launch the Bash shell.

On macOS, launch the Terminal.

On macOS, launch the Terminal.

On Windows, launch the Command Prompt from the Start Menu.

On Windows, launch the Command Prompt from the Start Menu.

2. Ensure that you are using the most current version of pip by running a command such as:

pip install -U pip

3. Run the following command to install the psycopg2 package:

pip install psycopg2

Get connection information

Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully qualified server name and login credentials.

1. Log in to the Azure portal.

3.

Click the server name.

4. From the server's Overview panel, make a note of the Server name and Server admin login name. If you forget your password, you can also reset the password from this panel.

password, you can also reset the password from this panel. How to run Python code This

How to run Python code

This article contains a total of four code samples, each of which performs a specific function. The following instructions indicate how to create a text file, insert a code block, and then save the file so that you can run it later. Be sure to create four separate files, one for each code block.

Using your favorite text editor, create a new file.sure to create four separate files, one for each code block. Copy and paste one of

Copy and paste one of the code samples in the following sections into the text file. Replace the host , dbname , user , and password parameters with the values that you specified host, dbname, user, and password parameters with the values that you specified when you created the server and database.

Save the file with the .py extension (for example postgres.py) into your project folder. If you are running on Windows, be sure to select UTF-8 encoding when saving the file.that you specified when you created the server and database. Launch the Command Prompt, Terminal, or

Launch the Command Prompt, Terminal, or Bash shell and then change the directory to your project folder, forbe sure to select UTF-8 encoding when saving the file. example cd postgres . To run

example

cd postgres

.

To run the code, type the Python command followed by the file name, for exampleto your project folder, for example cd postgres . Python postgres.py . NNOOTTEE Starting in Python

Python postgres.py

.

NNOOTTEE Starting in Python version 3, you may see the error

running the following code blocks: If that happens, replace each call to the command

using parenthesis, such as

SyntaxError: Missing parentheses in call to 'print'
SyntaxError: Missing parentheses in call to 'print'

SyntaxError: Missing parentheses in call to 'print'

SyntaxError: Missing parentheses in call to 'print' print "string"

print "string"

SyntaxError: Missing parentheses in call to 'print' print "string"

when

with a function call

print("string")

.

Connect, create table, and insert data

Use the following code to connect and load the data using psycopg2.connect function with INSERT SQL statement. The cursor.execute function is used to execute the SQL query against PostgreSQL database. Replace the host, dbname, user, and password parameters with the values that you specified when you created the server and database.

import psycopg2

# Update connection string information obtained from the portal host = "mydemoserver.postgres.database.azure.com" user = "mylogin@mydemoserver" dbname = "mypgsqldb" password = "<server_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 table

cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);") print "Finished creating table"

# Insert some data into 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"

# Cleanup

conn.commit()

cursor.close()

conn.close()

After the code runs successfully, the output appears as follows:

the code runs successfully, the output appears as follows: Read data Use the following code to

Read data

Use the following code to read the data inserted using cursor.execute function with SELECT SQL statement. This function accepts a query and returns a result set that can be iterated over with the use of cursor.fetchall(). Replace the host, dbname, user, and password parameters with the values that you specified when you created the server and database.

import psycopg2

# Update connection string information obtained from the portal host = "mydemoserver.postgres.database.azure.com" user = "mylogin@mydemoserver" dbname = "mypgsqldb" password = "<server_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()

Update data

Use the following code to update the inventory row that you previously inserted using cursor.execute function with UPDATE SQL statement. Replace the host, dbname, user, and password parameters with the values that you specified when you created the server and database.

import psycopg2

# Update connection string information obtained from the portal host = "mydemoserver.postgres.database.azure.com" user = "mylogin@mydemoserver" dbname = "mypgsqldb" password = "<server_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()

Delete data

Use the following code to delete an inventory item that you previously inserted using cursor.execute function with DELETE SQL statement. Replace the host, dbname, user, and password parameters with the values that you specified when you created the server and database.

import psycopg2

# Update connection string information obtained from the portal host = "mydemoserver.postgres.database.azure.com" user = "mylogin@mydemoserver" dbname = "mypgsqldb" password = "<server_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()

Next steps

Migrate your database using Export and Import

Azure Database for PostgreSQL: Use Node.js to connect and query data

2/27/2018 • 4 minutes to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a Node.js application. It shows how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article assume that you are familiar with developing using Node.js, and are new to working with Azure Database for PostgreSQL.

Prerequisites

This quickstart uses the resources created in either of these guides as a starting point:

Create DB - Portalcreated in either of these guides as a starting point: Create DB - CLI You also

Create DB - CLIof these guides as a starting point: Create DB - Portal You also need to: Install

You also need to:

Install Node.js Node.js

Install pg client

Install pg, which is a PostgreSQL client for Node.js.

To do so, run the node package manager (npm) for JavaScript from your command line to install the pg client.

npm install pg

Verify the installation by listing the packages installed.

npm list

Get connection information

Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully qualified server name and login credentials.

1. Log in to the Azure portal.

2. From the left-hand menu in Azure portal, click All resources, and then search for the server you have created (such as mydemoserver).

3. Click the server name.

4. From the server's Overview panel, make a note of the Server name and Server admin login name. If you forget your password, you can also reset the password from this panel.

Running the JavaScript code in Node.js You may launch Node.js from the Bash shell, Terminal,

Running the JavaScript code in Node.js

You may launch Node.js from the Bash shell, Terminal, or Windows Command Prompt by typing

the example JavaScript code interactively by copy and pasting it onto the prompt. Alternatively, you may save the

JavaScript code into a text file and launch

node
node

, then run

node filename.js

with the file name as a parameter to run it.

Connect, create table, and insert data

Use the following code to connect and load the data using CREATE TABLE and INSERT INTO SQL statements. The pg.Client object is used to interface with the PostgreSQL server. The pg.Client.connect() function is used to establish the connection to the server. The pg.Client.query() function is used to execute the SQL query against PostgreSQL database.

Replace the host, dbname, user, and password parameters with the values that you specified when you created the server and database.

const pg = require('pg');

const config = { host: '<your-db-server-name>.postgres.database.azure.com', // Do not hard code your username and password. // Consider using Node environment variables. user: '<your-db-username>', password: '<your-password>', database: '<name-of-database>', port: 5432, ssl: true

};

const client = new pg.Client(config);

client.connect(err => { if (err) throw err; else { queryDatabase();

});

}

function queryDatabase() { const query = ` DROP TABLE IF EXISTS inventory; CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER); INSERT INTO inventory (name, quantity) VALUES ('banana', 150); INSERT INTO inventory (name, quantity) VALUES ('orange', 154); INSERT INTO inventory (name, quantity) VALUES ('apple', 100);

`;

client .query(query) .then(() => { console.log('Table created successfully!'); client.end(console.log('Closed client connection'));

}) .catch(err => console.log(err)) .then(() => { console.log('Finished execution, exiting now'); process.exit();

});

}

Read data

Use the following code to connect and read the data using a SELECT SQL statement. The pg.Client object is used to interface with the PostgreSQL server. The pg.Client.connect() function is used to establish the connection to the server. The pg.Client.query() function is used to execute the SQL query against PostgreSQL database.

Replace the host, dbname, user, and password parameters with the values that you specified when you created the server and database.

const pg = require('pg');

const config = { host: '<your-db-server-name>.postgres.database.azure.com', // Do not hard code your username and password. // Consider using Node environment variables. user: '<your-db-username>', password: '<your-password>', database: '<name-of-database>', port: 5432, ssl: true

};

const client = new pg.Client(config);

client.connect(err => { if (err) throw err; else { queryDatabase(); }

});

function queryDatabase() {

console.log(`Running query to PostgreSQL server: ${config.host}`);

const query = 'SELECT * FROM inventory;';

client.query(query) .then(res => { const rows = res.rows;

rows.map(row => { console.log(`Read: ${JSON.stringify(row)}`);

});

process.exit();

}) .catch(err => { console.log(err);

});

}

Update data

Use the following code to connect and read the data using a UPDATE SQL statement. The pg.Client object is used to interface with the PostgreSQL server. The pg.Client.connect() function is used to establish the connection to the server. The pg.Client.query() function is used to execute the SQL query against PostgreSQL database.

Replace the host, dbname, user, and password parameters with the values that you specified when you created the server and database.

const pg = require('pg');

const config = { host: '<your-db-server-name>.postgres.database.azure.com', // Do not hard code your username and password. // Consider using Node environment variables. user: '<your-db-username>', password: '<your-password>', database: '<name-of-database>', port: 5432, ssl: true

};

const client = new pg.Client(config);

client.connect(err => { if (err) throw err; else { queryDatabase();

});

}

function queryDatabase() { const query = ` UPDATE inventory SET quantity= 1000 WHERE name='banana';

`;

client .query(query) .then(result => { console.log('Update completed'); console.log(`Rows affected: ${result.rowCount}`);

}) .catch(err => { console.log(err); throw err;

});

}

Delete data

Use the following code to connect and read the data using a DELETE SQL statement. The pg.Client object is used to interface with the PostgreSQL server. The pg.Client.connect() function is used to establish the connection to the server. The pg.Client.query() function is used to execute the SQL query against PostgreSQL database.

Replace the host, dbname, user, and password parameters with the values that you specified when you created the server and database.

const pg = require('pg');

const config = { host: '<your-db-server-name>.postgres.database.azure.com', // Do not hard code your username and password. // Consider using Node environment variables. user: '<your-db-username>', password: '<your-password>', database: '<name-of-database>', port: 5432, ssl: true

};

const client = new pg.Client(config);

client.connect(err => { if (err) { throw err; } else { queryDatabase();

});

}

function queryDatabase() { const query = ` DELETE FROM inventory WHERE name = 'apple';

`;

client .query(query) .then(result => { console.log('Delete completed'); console.log(`Rows affected: ${result.rowCount}`);

}) .catch(err => { console.log(err); throw err;

});

}

Next steps

Migrate your database using Export and Import

Azure Database for PostgreSQL: Use Java to connect and query data

2/27/2018 • 7 minutes to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a Java application. It shows how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article assume that you are familiar with developing using Java, and are new to working with Azure Database for PostgreSQL.

Prerequisites

This quickstart uses the resources created in either of these guides as a starting point:

Create DB - Portalcreated in either of these guides as a starting point: Create DB - Azure CLI You

Create DB - Azure CLIof these guides as a starting point: Create DB - Portal You also need to: Download

You also need to:

Download the PostgreSQL JDBC Driver matching your version of Java and the Java Development Kit. PostgreSQL JDBC Driver matching your version of Java and the Java Development Kit.

Include the PostgreSQL JDBC jar file (for example postgresql-42.1.1.jar) in your application classpath. For more information, see classpath details . classpath details.

Get connection information

Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully qualified server name and login credentials.

1. Log in to the Azure portal.

2. From the left-hand menu in Azure portal, click All resources, and then search for the server you have created (such as mydemoserver).

3. Click the server name.

4. From the server's Overview panel, make a note of the Server name and Server admin login name. If you forget your password, you can also reset the password from this panel.

password, you can also reset the password from this panel. Connect, create table, and insert data

Connect, create table, and insert data

Use the following code to connect and load the data into the database using the function with an INSERT SQL statement. The methods getConnection(), createStatement(), and executeQuery() are used to connect to the database, drop, and create the table. The prepareStatement object is used to build the insert commands, with setString() and setInt() to bind the parameter values. Method executeUpdate() runs the command for each set of parameters.

Replace the host, database, user, and password parameters with the values that you specified when you created your own server and database.

import java.sql.*; import java.util.Properties;

public class CreateTableInsertRows {

public static void main (String[] args) throws Exception

{

// Initialize connection variables. String host = "mydemoserver.postgres.database.azure.com"; String database = "mypgsqldb"; String user = "mylogin@mydemoserver"; String password = "<server_admin_password>";

// check that the driver is installed try

{

Class.forName("org.postgresql.Driver");

}

catch (ClassNotFoundException e)

{

throw new ClassNotFoundException("PostgreSQL JDBC driver NOT detected in library path.", e);

}

System.out.println("PostgreSQL JDBC driver detected in library path.");

Connection connection = null;

// Initialize connection object try

{

 

String url = String.format("jdbc:postgresql://%s/%s", host, database);

// set up the connection properties Properties properties = new Properties(); properties.setProperty("user", user); properties.setProperty("password", password); properties.setProperty("ssl", "true");

// get connection connection = DriverManager.getConnection(url, properties);

}

catch (SQLException e)

{

throw new SQLException("Failed to create connection to database.", e);

}

if (connection != null)

{

System.out.println("Successfully created connection to database.");

// Perform some SQL queries over the connection. try

{

// Drop previous table of same name if one exists. Statement statement = connection.createStatement(); statement.execute("DROP TABLE IF EXISTS inventory;"); System.out.println("Finished dropping table (if existed).");

// Create table. statement.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity

INTEGER);");

System.out.println("Created table.");

// Insert some data into table.

int nRowsInserted = 0; PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO inventory (name, quantity) VALUES (?, ?);"); preparedStatement.setString(1, "banana"); preparedStatement.setInt(2, 150); nRowsInserted += preparedStatement.executeUpdate();

preparedStatement.setString(1, "orange"); preparedStatement.setInt(2, 154); nRowsInserted += preparedStatement.executeUpdate();

preparedStatement.setString(1, "apple"); preparedStatement.setInt(2, 100); nRowsInserted += preparedStatement.executeUpdate(); System.out.println(String.format("Inserted %d row(s) of data.", nRowsInserted));

// NOTE No need to commit all changes to database, as auto-commit is enabled by default.

}

catch (SQLException e)

{

throw new SQLException("Encountered an error when executing given sql statement.", e);

}

}

else { System.out.println("Failed to create connection to database.");

}

System.out.println("Execution finished.");

}

}

Read data

Use the following code to read the data with a SELECT SQL statement. The methods getConnection(), createStatement(), and executeQuery() are used to connect to the database, create, and run the select statement. The results are processed using a ResultSet object.

Replace the host, database, user, and password parameters with the values that you specified when you created your own server and database.

import java.sql.*; import java.util.Properties;

public class ReadTable {

public static void main (String[] args) throws Exception

{

// Initialize connection variables. String host = "mydemoserver.postgres.database.azure.com"; String database = "mypgsqldb"; String user = "mylogin@mydemoserver"; String password = "<server_admin_password>";

// check that the driver is installed try

{

Class.forName("org.postgresql.Driver");

}

catch (ClassNotFoundException e)

{

throw new ClassNotFoundException("PostgreSQL JDBC driver NOT detected in library path.", e);

}

System.out.println("PostgreSQL JDBC driver detected in library path.");

Connection connection = null;

// Initialize connection object try

{

 

String url = String.format("jdbc:postgresql://%s/%s", host, database);

// set up the connection properties Properties properties = new Properties(); properties.setProperty("user", user); properties.setProperty("password", password); properties.setProperty("ssl", "true");

// get connection connection = DriverManager.getConnection(url, properties);

}

catch (SQLException e)

{

throw new SQLException("Failed to create connection to database.", e);

}

if (connection != null)

{

 

System.out.println("Successfully created connection to database.");

// Perform some SQL queries over the connection. try

{

 

Statement statement = connection.createStatement(); ResultSet results = statement.executeQuery("SELECT * from inventory;"); while (results.next())

{

String outputString = String.format( "Data row = (%s, %s, %s)",

results.getString(1),

results.getString(2),

results.getString(3));

System.out.println(outputString);

}

 

}

catch (SQLException e)

{

 

throw new SQLException("Encountered an error when executing given sql statement.", e);

 

}

}

else { System.out.println("Failed to create connection to database.");

}

System.out.println("Execution finished.");

}

}

Update data

Use the following code to change the data with an UPDATE SQL statement. The methods getConnection(), prepareStatement(), and executeUpdate() are used to connect to the database, prepare, and run the update statement.

Replace the host, database, user, and password parameters with the values that you specified when you created your own server and database.

public class UpdateTable {

public static void main (String[] args) throws Exception

{

// Initialize connection variables. String host = "mydemoserver.postgres.database.azure.com"; String database = "mypgsqldb"; String user = "mylogin@mydemoserver"; String password = "<server_admin_password>";

// check that the driver is installed try

{

Class.forName("org.postgresql.Driver");

}

catch (ClassNotFoundException e)

{

throw new ClassNotFoundException("PostgreSQL JDBC driver NOT detected in library path.", e);

}

System.out.println("PostgreSQL JDBC driver detected in library path.");

Connection connection = null;

// Initialize connection object try

{

 

String url = String.format("jdbc:postgresql://%s/%s", host, database);

// set up the connection properties Properties properties = new Properties(); properties.setProperty("user", user); properties.setProperty("password", password); properties.setProperty("ssl", "true");

// get connection connection = DriverManager.getConnection(url, properties);

}

catch (SQLException e)

{

throw new SQLException("Failed to create connection to database.", e);

}

if (connection != null)

{

System.out.println("Successfully created connection to database.");

// Perform some SQL queries over the connection. try

{

// Modify some data in table. int nRowsUpdated = 0; PreparedStatement preparedStatement = connection.prepareStatement("UPDATE inventory SET quantity = ? WHERE name = ?;"); preparedStatement.setInt(1, 200); preparedStatement.setString(2, "banana"); nRowsUpdated += preparedStatement.executeUpdate(); System.out.println(String.format("Updated %d row(s) of data.", nRowsUpdated));

// NOTE No need to commit all changes to database, as auto-commit is enabled by default.

}

catch (SQLException e)

{

throw new SQLException("Encountered an error when executing given sql statement.", e);

}

}

else { System.out.println("Failed to create connection to database.");

}

System.out.println("Execution finished.");

}

}

Delete data

Use the following code to remove data with a DELETE SQL statement. The methods getConnection(), prepareStatement(), and executeUpdate() are used to connect to the database, prepare, and run the delete statement.

Replace the host, database, user, and password parameters with the values that you specified when you created your own server and database.

import java.sql.*; import java.util.Properties;

public class DeleteTable {

public static void main (String[] args) throws Exception

{

// Initialize connection variables. String host = "mydemoserver.postgres.database.azure.com"; String database = "mypgsqldb"; String user = "mylogin@mydemoserver"; String password = "<server_admin_password>";

// check that the driver is installed try

{

Class.forName("org.postgresql.Driver");

}

catch (ClassNotFoundException e)

{

throw new ClassNotFoundException("PostgreSQL JDBC driver NOT detected in library path.", e);

}

System.out.println("PostgreSQL JDBC driver detected in library path.");

Connection connection = null;

// Initialize connection object try

{

 

String url = String.format("jdbc:postgresql://%s/%s", host, database);

// set up the connection properties Properties properties = new Properties(); properties.setProperty("user", user); properties.setProperty("password", password); properties.setProperty("ssl", "true");

// get connection connection = DriverManager.getConnection(url, properties);

}

catch (SQLException e)

{

throw new SQLException("Failed to create connection to database.", e);

}

if (connection != null)

{

System.out.println("Successfully created connection to database.");

// Perform some SQL queries over the connection. try

{

// Delete some data from table. int nRowsDeleted = 0; PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM inventory WHERE

name = ?;");

preparedStatement.setString(1, "orange"); nRowsDeleted += preparedStatement.executeUpdate(); System.out.println(String.format("Deleted %d row(s) of data.", nRowsDeleted));

// NOTE No need to commit all changes to database, as auto-commit is enabled by default.

}

catch (SQLException e)

{

throw new SQLException("Encountered an error when executing given sql statement.", e);

}

}

else { System.out.println("Failed to create connection to database.");

}

System.out.println("Execution finished.");

}

}

Next steps

Migrate your database using Export and Import

Azure Database for PostgreSQL: Use Ruby to connect and query data

2/27/2018 • 6 minutes to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a Ruby application. It shows how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article assume that you are familiar with developing using Ruby, and are new to working with Azure Database for PostgreSQL.

Prerequisites

This quickstart uses the resources created in either of these guides as a starting point:

Create DB - Portalcreated in either of these guides as a starting point: Create DB - Azure CLI Install

Create DB - Azure CLIof these guides as a starting point: Create DB - Portal Install Ruby Install Ruby on

Install Ruby

Install Ruby on your own machine.

WWiinnddoowwss

Download and Install the latest version of Ruby . Ruby.

On the finish screen of the MSI installer, check the box that says "Run 'ridk install' to install MSYS2 and development toolchain." Then click Finish to launch the next installer. Finish to launch the next installer.

The RubyInstaller2 for Windows installer launches. Type 2 to install the MSYS2 repository update. After it finishes and returns to the installation prompt, close the command window.Then click Finish to launch the next installer. Launch a new command prompt (cmd) from the

Launch a new command prompt (cmd) from the Start menu.to the installation prompt, close the command window. Test the Ruby installation Test the Gem installation

Test the Ruby installationLaunch a new command prompt (cmd) from the Start menu. Test the Gem installation Build the

Test the Gem installationprompt (cmd) from the Start menu. Test the Ruby installation Build the PostgreSQL module for Ruby

Build the PostgreSQL module for Ruby using Gem by running the commandmenu. Test the Ruby installation Test the Gem installation ruby -v gem -v to see the

ruby -v gem -v
ruby -v
gem -v

to see the version installed.

to see the version installed.

gem install pg .

MMaaccOOSS

Install Ruby using Homebrew by running the command the Ruby installation documentation installation documentation

Test the Ruby installationby running the command the Ruby installation documentation Test the Gem installation Build the PostgreSQL module

Test the Gem installationRuby installation documentation Test the Ruby installation Build the PostgreSQL module for Ruby using Gem by

Build the PostgreSQL module for Ruby using Gem by running the commandTest the Ruby installation Test the Gem installation brew install ruby . For more installation options,

brew install ruby

. For more installation options, see

ruby -v gem -v
ruby -v
gem -v

to see the version installed.

to see the version installed.

gem install pg .

LLiinnuuxx ((UUbbuunnttuu))

Install Ruby by running the command Ruby installation documentation . installation documentation.

Test the Ruby installationby running the command Ruby installation documentation . Install the latest updates for Gem by running

Install the latest updates for Gem by running the commandinstallation documentation . Test the Ruby installation Test the Gem installation Install the gcc, make, and

Test the Gem installationInstall the latest updates for Gem by running the command Install the gcc, make, and other

Install the gcc, make, and other build tools by running the commandfor Gem by running the command Test the Gem installation Install the PostgreSQL libraries by running

Install the PostgreSQL libraries by running the commandthe gcc, make, and other build tools by running the command Build the Ruby pg module

Build the Ruby pg module using Gem by running the commandInstall the PostgreSQL libraries by running the command sudo apt-get install ruby-full . For more installation

sudo apt-get install ruby-full

. For more installation options, see the

ruby -v
ruby -v
gem -v
gem -v

to see the version installed.

sudo gem update --system

.

to see the version installed.

sudo apt-get install build-essential

.

sudo apt-get install libpq-dev

.

sudo gem install pg

.

Run Ruby code

Run Ruby code Save the code into a text file with file extension .rb, and save

Save the code into a text file with file extension .rb, and save the file into a project folder, such as

C:\rubypostgres\read.rb

or

/home/username/rubypostgres/read.rb

cd rubypostgres
cd rubypostgres

To run the code, launch the command prompt or bash shell. Change directory into your project folder

, then type the command

ruby read.rb

to run the application.

Get connection information

Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully qualified server name and login credentials.

1. Log in to the Azure portal.

2. From the left-hand menu in Azure portal, click All resources, and then search for the server you have created (such as mydemoserver).

3. Click the server name.

4. From the server's Overview panel, make a note of the Server name and Server admin login name. If you forget your password, you can also reset the password from this panel.

password, you can also reset the password from this panel. Connect and create a table Use

Connect and create a table

Use the following code to connect and create a table using CREATE TABLE SQL statement, followed by INSERT INTO SQL statements to add rows into the table.

The code uses a PG::Connection object with constructor new() to connect to Azure Database for PostgreSQL. Then it calls method exec() to run the DROP, CREATE TABLE, and INSERT INTO commands. The code checks for errors using the PG::Error class. Then it calls method close() to close the connection before terminating.

Replace the

host , database , user
host
, database
, user

, and

password
password

strings with your own values.

require 'pg'

begin

# Initialize connection variables.

host = String('mydemoserver.postgres.database.azure.com') database = String('postgres') user = String('mylogin@mydemoserver') password = String('<server_admin_password>')

# Initialize connection object.

connection = PG::Connection.new(:host => host, :user => user, :dbname => database, :port => '5432',

:password => password) puts 'Successfully created connection to database'

# Drop previous table of same name if one exists

connection.exec('DROP TABLE IF EXISTS inventory;') puts 'Finished dropping table (if existed).'

# Drop previous table of same name if one exists.

connection.exec('CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);') puts 'Finished creating table.'

# Insert some data into table.

connection.exec("INSERT INTO inventory VALUES(1, 'banana', 150)") connection.exec("INSERT INTO inventory VALUES(2, 'orange', 154)") connection.exec("INSERT INTO inventory VALUES(3, 'apple', 100)") puts 'Inserted 3 rows of data.'

rescue PG::Error => e puts e.message

ensure connection.close if connection

end

Read data

Use the following code to connect and read the data using a SELECT SQL statement.

The code uses a PG::Connection object with constructor new() to connect to Azure Database for PostgreSQL. Then it calls method exec() to run the SELECT command, keeping the results in a result set. The result set collection is

iterated over using the

checks for errors using the PG::Error class. Then it calls method close() to close the connection before terminating.

Replace the

resultSet.each do

, and

loop, keeping the current row values in the

password
password

strings with your own values.

row
row

variable. The code

host , database , user
host
, database
, user

require 'pg'

begin

#

Initialize connection variables.

host = String('mydemoserver.postgres.database.azure.com')

database = String('postgres') user = String('mylogin@mydemoserver') password = String('<server_admin_password>')

# Initialize connection object.

connection = PG::Connection.new(:host => host, :user => user, :database => dbname, :port => '5432', :password => password) puts 'Successfully created connection to database.'

resultSet = connection.exec('SELECT * from inventory;') resultSet.each do |row| puts 'Data row = (%s, %s, %s)' % [row['id'], row['name'], row['quantity']]

end

rescue PG::Error => e puts e.message

ensure connection.close if connection

end

Update data

Use the following code to connect and update the data using a UPDATE SQL statement.

The code uses a PG::Connection object with constructor new() to connect to Azure Database for PostgreSQL. Then it calls method exec() to run the UPDATE command. The code checks for errors using the PG::Error class. Then it calls method close() to close the connection before terminating.

Replace the

host , database , user
host
, database
, user

, and

password
password

strings with your own values.

require 'pg'

begin

# Initialize connection variables.

host = String('mydemoserver.postgres.database.azure.com')

database = String('postgres') user = String('mylogin@mydemoserver') password = String('<server_admin_password>')

# Initialize connection object.

connection = PG::Connection.new(:host => host, :user => user, :dbname => database, :port => '5432', :password => password)

puts 'Successfully created connection to database.'

# Modify some data in table.

connection.exec('UPDATE inventory SET quantity = %d WHERE name = %s;' % [200, '\'banana\''])

puts 'Updated 1 row of data.'

rescue PG::Error => e puts e.message

ensure connection.close if connection

end

Delete data

Use the following code to connect and read the data using a DELETE SQL statement.

The code uses a PG::Connection object with constructor new() to connect to Azure Database for PostgreSQL. Then it calls method exec() to run the UPDATE command. The code checks for errors using the PG::Error class. Then it calls method close() to close the connection before terminating.

Replace the

host , database , user
host
, database
, user

, and

password
password

strings with your own values.

require 'pg'

begin

# Initialize connection variables.

host = String('mydemoserver.postgres.database.azure.com') database = String('postgres')

user = String('mylogin@mydemoserver') password = String('<server_admin_password>')

# Initialize connection object.

connection = PG::Connection.new(:host => host, :user => user, :dbname => database, :port => '5432', :password => password) puts 'Successfully created connection to database.'

# Modify some data in table.

connection.exec('DELETE FROM inventory WHERE name = %s;' % ['\'orange\'']) puts 'Deleted 1 row of data.'

rescue PG::Error => e puts e.message

ensure connection.close if connection

end

Next steps

Migrate your database using Export and Import

Azure Database for PostgreSQL: Use PHP to connect and query data

2/27/2018 • 6 minutes to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a PHP application. It shows how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article assume that you are familiar with developing using PHP, and are new to working with Azure Database for PostgreSQL.

Prerequisites

This quickstart uses the resources created in either of these guides as a starting point:

Create DB - Portalcreated in either of these guides as a starting point: Create DB - Azure CLI Install

Create DB - Azure CLIof these guides as a starting point: Create DB - Portal Install PHP Install PHP on

Install PHP

Install PHP on your own server, or create an Azure web app that includes PHP.

WWiinnddoowwss

Install PHP and refer to the PHP manual for further configuration PHP manual for further configuration

The code uses the pgsql class (ext/php_pgsql.dll) that is included in the PHP installation. pgsql class (ext/php_pgsql.dll) that is included in the PHP installation.

Enabled the pgsql extension by editing the php.ini configuration file, typically located at pgsql extension by editing the php.ini configuration file, typically located at

C:\Program Files\PHP\v7.1\php.ini

C:\Program Files\PHP\v7.1\php.ini

extension=php_pgsql.so

C:\Program Files\PHP\v7.1\php.ini extension=php_pgsql.so

. The configuration file should contain a line with the text

. If it is not shown, add the text and save the file. If the text is present, but commented

with a semicolon prefix, uncomment the text by removing the semicolon.

LLiinnuuxx ((UUbbuunnttuu))

Install PHP and refer to the PHP manual for further configuration PHP manual for further configuration

The code uses the pgsql class (php_pgsql.so). Install it by running pgsql class (php_pgsql.so). Install it by running

Enabled the pgsql extension by editing the pgsql extension by editing the

sudo apt-get install php-pgsql

.

/etc/php/7.0/mods-available/pgsql.ini
/etc/php/7.0/mods-available/pgsql.ini

/etc/php/7.0/mods-available/pgsql.ini

/etc/php/7.0/mods-available/pgsql.ini extension=php_pgsql.so

extension=php_pgsql.so

/etc/php/7.0/mods-available/pgsql.ini extension=php_pgsql.so

configuration file. The

configuration file should contain a line with the text

. If it is not shown, add the text and

save the file. If the text is present, but commented with a semicolon prefix, uncomment the text by removing the semicolon.

MMaaccOOSS

Install PHP and refer to the PHP manual for further configuration PHP manual for further configuration

Get connection information

Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully qualified server name and login credentials.

1. Log in to the Azure portal.

(such as mydemoserver).

3. Click the server name.

4. From the server's Overview panel, make a note of the Server name and Server admin login name. If you forget your password, you can also reset the password from this panel.

password, you can also reset the password from this panel. Connect and create a table Use

Connect and create a table

Use the following code to connect and create a table using CREATE TABLE SQL statement, followed by INSERT INTO SQL statements to add rows into the table.

The code call method pg_connect() to connect to Azure Database for PostgreSQL. Then it calls method pg_query() several times to run several commands, and pg_last_error() to check the details if an error occurred each time. Then it calls method pg_close() to close the connection.

Replace the

$host , $database , $user
$host
, $database
, $user

, and

$password
$password

parameters with your own values.

<?php // Initialize connection variables. $host = "mydemoserver.postgres.database.azure.com"; $database = "mypgsqldb"; $user = "mylogin@mydemoserver"; $password = "<server_admin_password>";

// Initialize connection object. $connection = pg_connect("host=$host dbname=$database user=$user password=$password") or die("Failed to create connection to database: ". pg_last_error(). "<br/>"); print "Successfully created connection to database.<br/>";

// Drop previous table of same name if one exists. $query = "DROP TABLE IF EXISTS inventory;"; pg_query($connection, $query) or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>"); print "Finished dropping table (if existed).<br/>";

// Create table. $query = "CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);"; pg_query($connection, $query) or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>"); print "Finished creating table.<br/>";

// Insert some data into table. $name = '\'banana\''; $quantity = 150; $query = "INSERT INTO inventory (name, quantity) VALUES ($1, $2);"; pg_query($connection, $query) or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>");

$name = '\'orange\''; $quantity = 154; $query = "INSERT INTO inventory (name, quantity) VALUES ($name, $quantity);"; pg_query($connection, $query) or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>");

$name = '\'apple\''; $quantity = 100; $query = "INSERT INTO inventory (name, quantity) VALUES ($name, $quantity);"; pg_query($connection, $query) or die("Encountered an error when executing given sql statement: ". pg_last_error()). "<br/>";

print "Inserted 3 rows of data.<br/>";

// Closing connection pg_close($connection);

?>

Read data

Use the following code to connect and read the data using a SELECT SQL statement.

The code call method pg_connect() to connect to Azure Database for PostgreSQL. Then it calls method pg_query() to run the SELECT command, keeping the results in a result set, and pg_last_error() to check the details if an error occurred. To read the result set, method pg_fetch_row() is called in a loop, once per row, and the row data is

retrieved in an array

pg_free_result() is called. Then it calls method pg_close() to close the connection.

Replace the

$row
$row

, with one data value per column in each array position. To free the result set, method

, and

$password
$password

parameters with your own values.

$host , $database , $user
$host
, $database
, $user

<?php // Initialize connection variables. $host = "mydemoserver.postgres.database.azure.com"; $database = "mypgsqldb"; $user = "mylogin@mydemoserver"; $password = "<server_admin_password>";

// Initialize connection object. $connection = pg_connect("host=$host dbname=$database user=$user password=$password") or die("Failed to create connection to database: ". pg_last_error(). "<br/>");

print "Successfully created connection to database. <br/>";

// Perform some SQL queries over the connection.

$query = "SELECT * from inventory"; $result_set = pg_query($connection, $query) or die("Encountered an error when executing given sql statement: ". pg_last_error(). "<br/>"); while ($row = pg_fetch_row($result_set))

{

print "Data row = ($row[0], $row[1], $row[2]). <br/>";

}

// Free result_set pg_free_result($result_set);

// Closing connection pg_close($connection);

?>

Update data

Use the following code to connect and update the data using a UPDATE SQL statement.

The code call method pg_connect() to connect to Azure Database for PostgreSQL. Then it calls method pg_query() to run a command, and pg_last_error() to check the details if an error occurred. Then it calls method pg_close() to close the connection.

Replace the

$host , $database , $user
$host
, $database
, $user

, and

$password
$password

parameters with your own values.

<?php // Initialize connection variables. $host = "mydemoserver.postgres.database.azure.com"; $database = "mypgsqldb"; $user = "mylogin@mydemoserver"; $password = "<server_admin_password>";

// Initialize connection object. $connection = pg_connect("host=$host dbname=$database user=$user password=$password") or die("Failed to create connection to database: ". pg_last_error(). ".<br/>");

print "Successfully created connection to database. <br/>";

// Modify some data in table. $new_quantity = 200; $name = '\'banana\''; $query = "UPDATE inventory SET quantity = $new_quantity WHERE name = $name;"; pg_query($connection, $query) or die("Encountered an error when executing given sql statement: ". pg_last_error(). ".<br/>"); print "Updated 1 row of data. </br>";

// Closing connection pg_close($connection);

?>

Delete data

Use the following code to connect and read the data using a DELETE SQL statement.

The code call method pg_connect() to connect to Azure Database for PostgreSQL. Then it calls method pg_query() to run a command, and pg_last_error() to check the details if an error occurred. Then it calls method pg_close() to close the connection.

Replace the

$host , $database , $user
$host
, $database
, $user

, and

$password
$password

parameters with your own values.

<?php // Initialize connection variables. $host = "mydemoserver.postgres.database.azure.com"; $database = "mypgsqldb"; $user = "mylogin@mydemoserver"; $password = "<server_admin_password>";

// Initialize connection object. $connection = pg_connect("host=$host dbname=$database user=$user password=$password") or die("Failed to create connection to database: ". pg_last_error(). ". </br>");

print "Successfully created connection to database. <br/>";

// Delete some data from table. $name = '\'orange\''; $query = "DELETE FROM inventory WHERE name = $name;"; pg_query($connection, $query) or die("Encountered an error when executing given sql statement: ". pg_last_error(). ". <br/>"); print "Deleted 1 row of data. <br/>";

// Closing connection pg_close($connection);

?>

Next steps

Migrate your database using Export and Import

Azure Database for PostgreSQL: Use .NET (C#) to connect and query data

2/27/2018 • 5 minutes to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using a C# application. It shows how to use SQL statements to query, insert, update, and delete data in the database. The steps in this article assume that you are familiar with developing using C#, and that you are new to working with Azure Database for PostgreSQL.

Prerequisites

This quickstart uses the resources created in either of these guides as a starting point:

Create DB - Portalcreated in either of these guides as a starting point: Create DB - CLI You also

Create DB - CLIof these guides as a starting point: Create DB - Portal You also need to: Install

You also need to:

Install the .NET Framework . Follow the steps in the linked article to install .NET specifically for .NET Framework. Follow the steps in the linked article to install .NET specifically for your platform (Windows, Ubuntu Linux, or macOS).

Install Visual Studio or Visual Studio Code to type and edit code. Visual Studio or Visual Studio Code to type and edit code.

Add a reference to the Npgsql Nuget package. Npgsql Nuget package.

Get connection information

Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully qualified server name and login credentials.

1. Log in to the Azure portal.

2. From the left-hand menu in Azure portal, click All resources, and then search for the server you have created (such as mydemoserver).

3. Click the server name.

4. From the server's Overview panel, make a note of the Server name and Server admin login name. If you forget your password, you can also reset the password from this panel.

password, you can also reset the password from this panel. Connect, create table, and insert data

Connect, create table, and insert data

Use the following code to connect and load the data using CREATE TABLE and INSERT INTO SQL statements. The code uses NpgsqlCommand class with method Open() to establish a connection to the PostgreSQL database. Then the code uses method CreateCommand(), sets the CommandText property, and calls the ExecuteNonQuery() method to run the database commands.

Replace the Host, DBName, User, and Password parameters with the values that you specified when you created the server and database.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Npgsql;

namespace Driver

{

public class AzurePostgresCreate

{

// Obtain connection string information from the portal // private static string Host = "mydemoserver.postgres.database.azure.com"; private static string User = "mylogin@mydemoserver"; private static string DBname = "mypgsqldb"; private static string Password = "<server_admin_password>"; private static string Port = "5432";

static void Main(string[] args)

{

// Build connection string using parameters from portal // string connString = String.Format( "Server={0}; User Id={1}; Database={2}; Port={3}; Password={4}; SSL Mode=Prefer; Trust Server Certificate=true", Host, User, DBname, Port, Password);

var conn = new NpgsqlConnection(connString);

Console.Out.WriteLine("Opening connection"); conn.Open();

var command = conn.CreateCommand(); command.CommandText = "DROP TABLE IF EXISTS inventory;"; command.ExecuteNonQuery(); Console.Out.WriteLine("Finished dropping table (if existed)");

command.CommandText = "CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity

INTEGER);";

command.ExecuteNonQuery(); Console.Out.WriteLine("Finished creating table");

command.CommandText = String.Format( @"

INSERT INTO inventory (name, quantity) VALUES ({0}, {1}); INSERT INTO inventory (name, quantity) VALUES ({2}, {3}); INSERT INTO inventory (name, quantity) VALUES ({4}, {5});

",

"\'banana\'", 150,

"\'orange\'", 154,

"\'apple\'", 100

);

int nRows = command.ExecuteNonQuery(); Console.Out.WriteLine(String.Format("Number of rows inserted={0}", nRows));

Console.Out.WriteLine("Closing connection");

conn.Close();

Console.WriteLine("Press RETURN to exit"); Console.ReadLine();

}

}

}

Read data

Use the following code to connect and read the data using a SELECT SQL statement. The code uses NpgsqlCommand class with method Open() to establish a connection to PostgreSQL. Then the code uses the methods CreateCommand() and ExecuteReader() to run the database commands. Next, the code uses Read() to advance to the record in the results. Finally, the code uses GetInt32() and GetString() to parse the values in the record.

Replace the Host, DBName, User, and Password parameters with the values that you specified when you created the server and database.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Npgsql;

namespace Driver

 

{

public class AzurePostgresRead

{

 

// Obtain connection string information from the portal // private static string Host = "mydemoserver.postgres.database.azure.com"; private static string User = "mylogin@mydemoserver"; private static string DBname = "mypgsqldb"; private static string Password = "<server_admin_password>"; private static string Port = "5432";

static void Main(string[] args)

{

 

// Build connection string using parameters from portal // string connString = String.Format( "Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};", Host, User, DBname, Port, Password);

var conn = new NpgsqlConnection(connString);

Console.Out.WriteLine("Opening connection"); conn.Open();

var command = conn.CreateCommand(); command.CommandText = "SELECT * FROM inventory;";

var reader = command.ExecuteReader(); while (reader.Read())

{

 

Console.WriteLine(

string.Format(

"Reading from table=({0}, {1}, {2})",

reader.GetInt32(0).ToString(),

reader.GetString(1),

reader.GetInt32(2).ToString()

)

);

 

}

Console.Out.WriteLine("Closing connection"); conn.Close();

Console.WriteLine("Press RETURN to exit"); Console.ReadLine();

 

}

}

}

Update data

Use the following code to connect and update the data using an UPDATE SQL statement. The code uses

NpgsqlCommand class with method Open() to establish a connection to PostgreSQL. Then, the code uses method CreateCommand(), sets the CommandText property, and calls the ExecuteNonQuery() method to run the database commands.

Replace the Host, DBName, User, and Password parameters with the values that you specified when you created the server and database.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Npgsql;

namespace Driver

 

{

public class AzurePostgresUpdate

{

 

// Obtain connection string information from the portal // private static string Host = "mydemoserver.postgres.database.azure.com"; private static string User = "mylogin@mydemoserver"; private static string DBname = "mypgsqldb"; private static string Password = "<server_admin_password>"; private static string Port = "5432";

static void Main(string[] args)

{

// Build connection string using parameters from portal // string connString = String.Format( "Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};", Host, User, DBname, Port, Password);

var conn = new NpgsqlConnection(connString);

Console.Out.WriteLine("Opening connection"); conn.Open();

var command = conn.CreateCommand(); command.CommandText = String.Format("UPDATE inventory SET quantity = {0} WHERE name = {1};",

 

200,

"\'banana\'"

);

 

int nRows = command.ExecuteNonQuery(); Console.Out.WriteLine(String.Format("Number of rows updated={0}", nRows));

Console.Out.WriteLine("Closing connection"); conn.Close();

Console.WriteLine("Press RETURN to exit"); Console.ReadLine();

}

}

}

Delete data

Use the following code to connect and delete data using a DELETE SQL statement.

The code uses NpgsqlCommand class with method Open() to establish a connection to the PostgreSQL database. Then, the code uses the CreateCommand() method, sets the CommandText property, and calls the method ExecuteNonQuery() to run the database commands.

Replace the Host, DBName, User, and Password parameters with the values that you specified when you created the server and database.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Npgsql;

namespace Driver

{

public class AzurePostgresDelete

{

 

// Obtain connection string information from the portal // private static string Host = "mydemoserver.postgres.database.azure.com"; private static string User = "mylogin@mydemoserver"; private static string DBname = "mypgsqldb"; private static string Password = "<server_admin_password>"; private static string Port = "5432";

static void Main(string[] args)

{

// Build connection string using parameters from portal // string connString = String.Format( "Server={0}; User Id={1}; Database={2}; Port={3}; Password={4};", Host, User, DBname, Port, Password);

var conn = new NpgsqlConnection(connString);

Console.Out.WriteLine("Opening connection"); conn.Open();

var command = conn.CreateCommand(); command.CommandText = String.Format("DELETE FROM inventory WHERE name = {0};", "\'orange\'"); int nRows = command.ExecuteNonQuery(); Console.Out.WriteLine(String.Format("Number of rows deleted={0}", nRows));

Console.Out.WriteLine("Closing connection"); conn.Close();

Console.WriteLine("Press RETURN to exit"); Console.ReadLine();

}

}

}

Next steps

Migrate your database using Export and Import

Azure Database for PostgreSQL: Use Go language to connect and query data

5/21/2018 • 8 minutes to read • Edit Online

This quickstart demonstrates how to connect to an Azure Database for PostgreSQL using code written in the Go language (golang). It shows how to use SQL statements to query, insert, update, and delete data in the database. This article assumes you are familiar with development using Go, but that you are new to working with Azure Database for PostgreSQL.

Prerequisites

This quickstart uses the resources created in either of these guides as a starting point:

Create DB - Portalcreated in either of these guides as a starting point: Create DB - Azure CLI Install

Create DB - Azure CLIof these guides as a starting point: Create DB - Portal Install Go and pq connector

Install Go and pq connector

Install Go and the Pure Go Postgres driver (pq) on your own machine. Depending on your platform, follow the appropriate steps:

WWiinnddoowwss

1. Download and install Go for Microsoft Windows according to the installation instructions.

2. Launch the command prompt from the start menu.

3. Make a folder for your project, such as

4. Change directory into the project folder, such as

5. Set the environment variable for GOPATH to point to the source code directory.

6. Install the Pure Go Postgres driver (pq) by running the

mkdir %USERPROFILE%\go\src\postgresqlgo

.

cd %USERPROFILE%\go\src\postgresqlgo

.

go get github.com/lib/pq

set GOPATH=%USERPROFILE%\go

.

command.

In summary, install Go, then run these commands in the command prompt:

mkdir %USERPROFILE%\go\src\postgresqlgo

cd %USERPROFILE%\go\src\postgresqlgo

set GOPATH=%USERPROFILE%\go

go get github.com/lib/pq

LLiinnuuxx ((UUbbuunnttuu))

1. Launch the Bash shell.

2. Install Go by running

3. Make a folder for your project in your home directory, such as

4. Change directory into the folder, such as

5. Set the GOPATH environment variable to point to a valid source directory, such as your current home

sudo apt-get install golang-go

.

mkdir -p ~/go/src/postgresqlgo/

.

cd ~/go/src/postgresqlgo/

.

directory's go folder. At the bash shell, run

current shell session.

export GOPATH=~/go

to add the go directory as the GOPATH for the

6. Install the Pure Go Postgres driver (pq) by running the

go get github.com/lib/pq

command.

In summary, run these bash commands:

sudo apt-get install golang-go

mkdir -p ~/go/src/postgresqlgo/

cd ~/go/src/postgresqlgo/

export GOPATH=~/go/

go get github.com/lib/pq

AAppppllee mmaaccOOSS

1. Download and install Go according to the installation instructions matching your platform.

2. Launch the Bash shell.

3. Make a folder for your project in your home directory, such as

4. Change directory into the folder, such as

5. Set the GOPATH environment variable to point to a valid source directory, such as your current home

mkdir -p ~/go/src/postgresqlgo/

.

cd ~/go/src/postgresqlgo/

.

directory's go folder. At the bash shell, run

current shell session.

export GOPATH=~/go

to add the go directory as the GOPATH for the

6. Install the Pure Go Postgres driver (pq) by running the

go get github.com/lib/pq

command.

In summary, install Go, then run these bash commands:

mkdir -p ~/go/src/postgresqlgo/

cd ~/go/src/postgresqlgo/

export GOPATH=~/go/

go get github.com/lib/pq

Get connection information

Get the connection information needed to connect to the Azure Database for PostgreSQL. You need the fully qualified server name and login credentials.

1. Log in to the Azure portal.

2. From the left-hand menu in Azure portal, click All resources, and then search for the server you have created (such as mydemoserver).

3. Click the server name.

4. From the server's Overview panel, make a note of the Server name and Server admin login name. If you forget your password, you can also reset the password from this panel.

password, you can also reset the password from this panel. Build and run Go code 1.

Build and run Go code

1. To write Golang code, you can use a plain text editor, such as Notepad in Microsoft Windows, vi or Nano in Ubuntu, or TextEdit in macOS. If you prefer a richer Interactive Development Environment (IDE) try Gogland by Jetbrains, Visual Studio Code by Microsoft, or Atom.

2. Paste the Golang code from the following sections into text files, and save into your project folder with file

extension *.go, such as Windows path

%USERPROFILE%\go\src\postgresqlgo\createtable.go

~/go/src/postgresqlgo/createtable.go

.

or Linux path

3. Locate the HOST , DATABASE , USER your own values.
3. Locate the
HOST
, DATABASE
, USER
your own values.

, and

PASSWORD
PASSWORD

constants in the code, and replace the example values with

4. Launch the command prompt or bash shell. Change directory into your project folder. For example, on

Windows

environments mentioned offer debug and runtime capabilities without requiring shell commands.

cd %USERPROFILE%\go\src\postgresqlgo\

. On Linux

cd ~/go/src/postgresqlgo/

. Some of the IDE

5. Run the code by typing the command

6. Alternatively, to build the code into a native application, to run the application.

go run createtable.go

to compile the application and run it.

, then launch

go build createtable.go

createtable.exe

Connect and create a table

Use the following code to connect and create a table using CREATE TABLE SQL statement, followed by INSERT INTO SQL statements to add rows into the table.

The code imports three packages: the sql package, the pq package as a driver to communicate with the PostgreSQL server, and the fmt package for printed input and output on the command line.

The code calls method sql.Open() to connect to Azure Database for PostgreSQL database, and checks the connection using method db.Ping(). A database handle is used throughout, holding the connection pool for the database server. The code calls the Exec() method several times to run several SQL commands. Each time a custom checkError() method checks if an error occurred and panic to exit if an error does occur.

Replace the

HOST , DATABASE , USER
HOST
, DATABASE
, USER

, and

PASSWORD
PASSWORD

parameters with your own values.

package main

import ( "database/sql" "fmt" _ "github.com/lib/pq"

)

const ( // Initialize connection constants.

)

HOST

DATABASE = "mypgsqldb"

USER

PASSWORD = "<server_admin_password>"

= "mydemoserver.postgres.database.azure.com"

= "mylogin@mydemoserver"

func checkError(err error) { if err != nil { panic(err)

}

}

func main() { // Initialize connection string. var connectionString string = fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=require", HOST, USER, PASSWORD, DATABASE)

// Initialize connection object. db, err := sql.Open("postgres", connectionString) checkError(err)

err = db.Ping() checkError(err) fmt.Println("Successfully created connection to database")

// Drop previous table of same name if one exists. _, err = db.Exec("DROP TABLE IF EXISTS inventory;") checkError(err) fmt.Println("Finished dropping table (if existed)")