Google Cloud SQL for PostgreSQL is an enterprise-grade, developer-friendly service that offers powerful AI-enhanced tools, helping developers reduce the time spent on database management. It provides a reliable and advanced platform that combines the convenience of a fully managed cloud service with the flexibility and performance of PostgreSQL.

With full compatibility across major PostgreSQL versions, support for popular extensions, more than 100 configurable database flags, and integration with key Google Cloud services such as Google Kubernetes Engine (GKE), BigQuery, and Cloud Run, Cloud SQL for PostgreSQL is a top choice for developers building cloud-native applications that demand enterprise-level features.

This tutorial demonstrates how to connect C# applications to a PostgreSQL instance hosted on Google Cloud using ADO.NET and dotConnect for PostgreSQL. You'll learn how to set up the connection and perform essential database operations directly from your .NET codebase.

Why dotConnect for PostgreSQL?

ORM support provided

Advanced ORM support

Fully supports EF Core, Dapper, NHibernate, LinqConnect, and other modern data access technologies for efficient and reliable data management.

Full ADO.NET compliance

Full ADO.NET compliance

Conforms to the latest ADO.NET standards and recent industry innovations for seamless and consistent integration with .NET applications.

Support for MySQL-specific data types

PostgreSQL-specific data types

Includes many PostgreSQL-specific features and fully supports all unique data types for accurate and complete data representation.

Secure connection ensured

Secure connection options

Provides robust security with support for SSL/SSH connections, connecting via proxy servers, embedded servers, and HTTP tunneling.

Integration with popular IDEs

IDE integration

Features native integration with Visual Studio and complete design-time support for accelerated development.

Priority support provided

Priority support & frequent updates

Includes priority support, detailed documentation, and regular updates for continuous improvement.

Download and activate dotConnect for PostgreSQL

You can start using dotConnect for PostgreSQL immediately with a 30-day free trial. Choose one of the following installation options:

30-day free trial version

dotnet add package Devart.Data.PostgreSql
Install-Package Devart.Data.PostgreSql

You can install the driver by using the Windows installer.

After you receive the license key, add it to your connection strings to connect to the data source.

Start using dotConnect for PostgreSQL in your project today with a free trial

Connect to Cloud SQL for PostgreSQL with Data Explorer

Let us connect to Cloud SQL for PostgreSQL with the help of the built-in Data Explorer. Click Tools, then select Connect to Database, and choose PostgreSQL as the data source.

Connect to a database in Cloud SQL for PostgreSQL using the Data Explorer

By default, Google Cloud for PostgreSQL requires an SSL connection. To enable it, go to the Google Cloud Console > SQL > your PostgreSQL instance > Connections > Security > Certificates, and download the Server CA certificate.

Find and download the Server CA certificate

Open Advanced Properties in your application and specify the downloaded certificate file under the SSL configuration before connecting.

Provide the required information to enable an SSL connection for Google Cloud

Enter your server details and credentials, and click Connect.

Successful connection to a Cloud SQL for PostgreSQL

Once connected, you can browse tables, execute queries, and manage data directly within the Data Explorer.

View the PostgreSQL data stored in Cloud SQL for PostgreSQL in the Data Explorer

Connect and retrieve data from the database

Let us establish a connection with Cloud SQL for PostgreSQL and then run a simple SELECT query to pull records from the Actor table. It confirms the connection is working properly and the data is accessible.

Create the DatabaseConnection.cs class (connection strings)

The DatabaseConnection.cs class keeps connection details separate for better maintainability.

using Devart.Data.PostgreSql;

public static class DatabaseConnection
{
    public static PgSqlConnection CreateConnection()
    {
        string connectionString = "" +
          "Server=127.0.0.1;" +
          "User Id=TestUser;" +
          "Password=TestPassword;" +
          "Database=TestDatabase;" +
          "Initial Schema=public;" +
          "SSLMode=Allow;" +
          "SSL CA Cert=file://C:\\server-ca.pem" +
          "License key=**********";

        return new PgSqlConnection(connectionString);
    }
}

Connection strings

Property Description
Host or Server Host name or IP address of the PostgreSQL server
User Id User ID used to authenticate with PostgreSQL
Password Password for the user ID
Database Default database to use after connecting
Schema PostgreSQL schema to use
Port Port on which the PostgreSQL server listens
License key Your license key (only required when you use .NET Standard-compatible assemblies)

Update the connection string

Replace the placeholders in the connection string with your actual PostgreSQL database credentials. If you own a paid license of dotConnect for PostgreSQL, include the license key in the connection strings.

Add the code below to your Program.cs file.

using Devart.Data.PostgreSql;

public sealed class Program
{
    public static void Main(string[] args)
    {
        try
        {
            using (PgSqlConnection connection = DatabaseConnection.CreateConnection())
            {
                connection.Open();
                Console.WriteLine("Connection successful!\n");

                string sql = "SELECT actor_id, first_name, last_name FROM actor ORDER BY actor_id LIMIT 10";
                using (PgSqlCommand command = new PgSqlCommand(sql, connection))
                using (PgSqlDataReader reader = command.ExecuteReader())
                {
                    Console.WriteLine("+---------+----------------+----------------+");
                    Console.WriteLine("| ActorId | First Name     | Last Name      |");
                    Console.WriteLine("+---------+----------------+----------------+");

                    while (reader.Read())
                    {
                        int actorId = reader.GetInt32(0);
                        string firstName = reader.GetString(1);
                        string lastName = reader.GetString(2);

                        Console.WriteLine($"| {actorId,-7} | {firstName,-14} | {lastName,-14} |");
                    }

                    Console.WriteLine("+---------+----------------+----------------+");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

Run the application

Build and run your application: select Start from the menu or click F5. It displays the data retrieved from the database.

Get data from the database in Cloud SQL for PostgreSQL

Insert new records into Cloud SQL for PostgreSQL

Let's add a new row to the Actor table by executing an INSERT command. See how to prepare and execute an INSERT statement from C# using standard ADO.NET code.

using Devart.Data.PostgreSql;

public sealed class Program
{
    public static void Main(string[] args)
    {
        try
        {
            using (PgSqlConnection connection = DatabaseConnection.CreateConnection())
            {
                connection.Open();
                Console.WriteLine("Connection successful!");

                string insertSql = "INSERT INTO actor(first_name, last_name) VALUES(@first, @last) RETURNING actor_id";
                using (PgSqlCommand insertCmd = new PgSqlCommand(insertSql, connection))
                {
                    insertCmd.Parameters.AddWithValue("@first", "TestFirst");
                    insertCmd.Parameters.AddWithValue("@last", "TestLast");
                    object result = insertCmd.ExecuteScalar();

                    long newActorId = 0;
                    if (result != null && result != DBNull.Value)
                    {
                        newActorId = Convert.ToInt64(result);
                    }

                    Console.WriteLine("+---------+----------------+----------------+");
                    Console.WriteLine("| ActorId | First Name     | Last Name      |");
                    Console.WriteLine("+---------+----------------+----------------+");
                    Console.WriteLine($"| {newActorId,-7} | {"TestFirst",-14} | {"TestLast",-14} |");
                    Console.WriteLine("+---------+----------------+----------------+");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

We can see the results in the application:

Successfully inserted record in a Cloud SQL for PostgreSQL database

Update rows in Cloud SQL for PostgreSQL

Next, we want to update an existing record: let us change the actor's first and last name. The following code shows how to build and run an UPDATE command from the application to modify data already stored in the database.

using Devart.Data.PostgreSql;

public sealed class Program
{
    public static void Main(string[] args)
    {
        try
        {
            using (PgSqlConnection connection = DatabaseConnection.CreateConnection())
            {
                connection.Open();
                Console.WriteLine("Connection successful!");

                long actorId = 202;
                string firstName = "James";
                string lastName = "Johnson";

                string updateSql = "UPDATE actor SET first_name = @first, last_name = @last WHERE actor_id = @id";
                using (PgSqlCommand updateCmd = new PgSqlCommand(updateSql, connection))
                {
                    updateCmd.Parameters.AddWithValue("@first", firstName);
                    updateCmd.Parameters.AddWithValue("@last", lastName);
                    updateCmd.Parameters.AddWithValue("@id", actorId);

                    int rowsAffected = updateCmd.ExecuteNonQuery();

                    if (rowsAffected > 0)
                    {
                        Console.WriteLine("+---------+----------------+----------------+");
                        Console.WriteLine("| ActorId | First Name     | Last Name      |");
                        Console.WriteLine("+---------+----------------+----------------+");
                        Console.WriteLine($"| {actorId,-7} | {firstName,-14} | {lastName,-14} |");
                        Console.WriteLine("+---------+----------------+----------------+");
                    }
                    else
                    {
                        Console.WriteLine($"No actor found with actor_id: {actorId}");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

Our application shows that the operation is successful:

Successfully updated record in a Cloud SQL for PostgreSQL database

Delete rows from Cloud SQL for PostgreSQL

Finally, let us see how to delete the record for that actor we have just added to the database. We run the DELETE statement and remove rows based on a condition in a query.

using Devart.Data.PostgreSql;

public sealed class Program
{
    public static void Main(string[] args)
    {
        try
        {
            using (PgSqlConnection connection = DatabaseConnection.CreateConnection())
            {
                connection.Open();
                Console.WriteLine("Connection successful!");

                long actorId = 202;

                string deleteSql = "DELETE FROM actor WHERE actor_id = @id";
                using (PgSqlCommand deleteCmd = new PgSqlCommand(deleteSql, connection))
                {
                    deleteCmd.Parameters.AddWithValue("@id", actorId);

                    int rowsAffected = deleteCmd.ExecuteNonQuery();

                    if (rowsAffected > 0)
                    {
                        Console.WriteLine($"+---------+");
                        Console.WriteLine("| ActorId |");
                        Console.WriteLine("+---------+");
                        Console.WriteLine($"| {actorId,-7} |");
                        Console.WriteLine("+---------+");
                        Console.WriteLine($"Actor with actor_id {actorId} has been removed.");
                    }
                    else
                    {
                        Console.WriteLine($"No actor found with actor_id: {actorId}");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

The command is executed correctly, and the output in the application confirms that the record has been deleted.

Successfully deleted record from the Cloud SQL for PostgreSQL database

Conclusion

Now that you know the essentials of connecting to and working with databases hosted in Google's Cloud SQL for PostgreSQL from a .NET application, you can connect, query, insert, update, and delete records easily.

With these fundamentals in place, you can proceed to more complex techniques and build applications that take full advantage of PostgreSQL in the cloud, while dotConnect for PostgreSQL ensures a smooth, secure, and efficient connection experience.

FAQ

How do you install and activate dotConnect for PostgreSQL in a .NET project?
Install dotConnect for PostgreSQL either by running the Windows installer (EXE) or by adding the Devart.Data.PostgreSql NuGet package to your .NET project. Then, retrieve your activation key from the Devart Customer Portal and specify it in your connection string by using the License Key parameter to activate the provider and connect successfully.
How do you create a connection to PostgreSQL using dotConnect in C#?
Define a connection string that includes Host, User Id, Password, Database, and (if required) License Key. Then create a PgSqlConnection with this string and call Open() inside a try/catch block to verify the connection and handle any errors.
How do you enable SSL/TLS for secure PostgreSQL connections with dotConnect?
Add SslMode=Require and provide the certificate file paths (for example, CACert, Cert, and Key) in the connection string. Then create a PgSqlConnection with this string and call Open() to establish an encrypted SSL/TLS session.
Can you connect to PostgreSQL using Entity Framework Core and dotConnect?
Yes, you can connect to PostgreSQL using Entity Framework Core and dotConnect. You can either use Entity Developer to visually create an EF Core model from the database and generate the DbContext and entity classes, or run Scaffold-DbContext with a dotConnect connection string (including the License Key) to scaffold the DbContext and entities from an existing database.
Is it possible to connect to PostgreSQL using Visual Studio Server Explorer with dotConnect?
Yes. In Visual Studio Server Explorer, you can add a new Data Connection, select dotConnect for PostgreSQL as the data provider, enter your PostgreSQL connection details, test the connection, and then browse and work with database objects directly in the IDE.

Dereck Mushingairi

I'm a technical content writer who loves turning complex topics — think SQL, connectors, and backend chaos–into content that actually makes sense (and maybe even makes you smile). I write for devs, data folks, and curious minds who want less fluff and more clarity. When I'm not wrangling words, you'll find me dancing salsa, or hopping between cities.

dotConnect for PostgreSQL

Get an enhanced ORM-enabled data provider for PostgreSQL and develop .NET applications working with PostgreSQL data quickly and easily!

Try the 30-day trial of the full product. No limits. No card required. Start free trial