Google Cloud offers a reliable and scalable MySQL service through Cloud SQL, making it easy to run managed relational databases in the cloud. For .NET developers, integrating a MySQL instance on Google Cloud into your application can streamline data access while offloading infrastructure management.

In this tutorial, you'll learn how to connect your C# application to a MySQL database hosted on Google Cloud and perform basic data operations such as querying, inserting, updating, and deleting records. This guide is ideal for developers new to cloud integrations with .NET.

Why dotConnect for MySQL?

ORM support provided

Advanced ORM support

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

Full ADO.NET compliance

Full ADO.NET compliance

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

Support for MySQL-specific data types

MySQL-specific data types

Offers many MySQL-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 MySQL

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

30-day free trial version

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

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 MySQL in your project today with a free trial

Check MySQL database objects

To connect to MySQL using the built-in Data Explorer, click Tools and select Connect to Database. Then choose MySQL Server as the data source.

Choose the data source

By default, Google Cloud for MySQL requires an SSL connection.

To enable it, go to the Google Cloud Console → SQL → your MySQL instance → Connections → Security → Certificates, and download the Server CA certificate.

Download CA certificate

Then, open the Advanced connection settings in your application and specify the path to the downloaded certificate file under the SSL configuration before connecting.

Specify certificate details

Enter your server details and credentials and click Connect.

Connect to the server

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

Browse the database

Connect to the database and retrieve data

First, let's establish a connection to your Cloud SQL for MySQL instance and run a simple query to pull records from the Actor table. This step ensures that your application is communicating properly with the database.

Create DatabaseConnection.cs (connection strings)

This class keeps connection details separate for better maintainability.

using Devart.Data.MySql;

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

        return new MySqlConnection(connectionString);
    }
}

Connection strings

Property Meaning
Host or Server Hostname or IP address of the MySQL server
Port Port number on which the MySQL server is listening
User Id User ID used to authenticate with MySQL
Password Password for the user ID
Database Default database to be used after connecting
License key Your license key (only required when using .NET Standard compatible assemblies)

Update the connection string

Replace the placeholders in the connection string with your actual MySQL database credentials.

Note
If you have a paid license of dotConnect for MySQL, include the license key in the connection strings.

Add the code below to your Program.cs file.

using Devart.Data.MySql;

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

                string sql = "SELECT actor_id, first_name, last_name FROM actor ORDER BY actor_id LIMIT 10";
                using (MySqlCommand command = new MySqlCommand(sql, connection))
                using (MySqlDataReader reader = command.ExecuteReader())
                {
                    Console.WriteLine("ActorId\tFirstName\tLastName");
                    while (reader.Read())
                    {
                        int actorId = reader.GetInt32(0);
                        string firstName = reader.GetString(1);
                        string lastName = reader.GetString(2);
                        Console.WriteLine(actorId + "\t" + firstName + "\t" + lastName);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

Run the application

Build and run your application by pressing F5 or selecting Start from the menu.

Run the application

Insert new records in MySQL

Now that the connection is active, let's add new data. In this example, you will learn how to insert a row into the Actor table using parameterized SQL to write data into your MySQL instance safely.

using Devart.Data.MySql;

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

                string insertSql = "INSERT INTO actor(first_name, last_name) VALUES(@first, @last)";
                using (MySqlCommand insertCmd = new MySqlCommand(insertSql, connection))
                {
                    insertCmd.Parameters.AddWithValue("@first", "TestFirst");
                    insertCmd.Parameters.AddWithValue("@last", "TestLast");
                    insertCmd.ExecuteNonQuery();
                }

                long newActorId = 0;
                using (MySqlCommand idCmd = new MySqlCommand("SELECT LAST_INSERT_ID()", connection))
                {
                    object result = idCmd.ExecuteScalar();
                    if (result != null && result != DBNull.Value)
                    {
                        newActorId = Convert.ToInt64(result);
                    }
                }

                Console.WriteLine("Inserted test actor (actor_id: " + newActorId + "): TestFirst TestLast");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

You can see the results in your application:

Insert data

Update rows in MySQL

Need to modify existing data? In this example, let's update the first and last names of an actor in the table, applying changes to a specific row using a targeted update statement.

using Devart.Data.MySql;

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

                string updateSql = "UPDATE actor SET first_name = @first, last_name = @last WHERE actor_id = @id";
                using (MySqlCommand updateCmd = new MySqlCommand(updateSql, connection))
                {
                    updateCmd.Parameters.AddWithValue("@first", "Michael");
                    updateCmd.Parameters.AddWithValue("@last", "Anderson");
                    updateCmd.Parameters.AddWithValue("@id", 205);
                    int rowsAffected = updateCmd.ExecuteNonQuery();

                    if (rowsAffected > 0)
                    {
                        Console.WriteLine("Updated actor: Michael Anderson");

                        // Retrieve and display the updated row
                        string selectSql = "SELECT actor_id, first_name, last_name FROM actor WHERE actor_id = @id";
                        using (MySqlCommand selectCmd = new MySqlCommand(selectSql, connection))
                        {
                            selectCmd.Parameters.AddWithValue("@id", 205);
                            using (MySqlDataReader reader = selectCmd.ExecuteReader())
                            {
                                if (reader.Read())
                                {
                                    Console.WriteLine($"actor_id: {reader["actor_id"]}, first_name: {reader["first_name"]}, last_name: {reader["last_name"]}");
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("No actor found with actor_id: 205");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

You can see the results in your application:

Update data

Delete rows in MySQL

To clean up the test data, let's delete the actor we just added. This demonstrates how to remove records from a MySQL database on Google Cloud using standard SQL commands in C#.

using Devart.Data.MySql;

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

                string deleteSql = "DELETE FROM actor WHERE actor_id = @id";
                using (MySqlCommand deleteCmd = new MySqlCommand(deleteSql, connection))
                {
                    deleteCmd.Parameters.AddWithValue("@id", 205);
                    int rowsAffected = deleteCmd.ExecuteNonQuery();

                    if (rowsAffected > 0)
                    {
                        Console.WriteLine("Deleted actor with actor_id: 205");
                    }
                    else
                    {
                        Console.WriteLine("No actor found with actor_id: 205");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

The application output shows that the operation is successful.

Delete data

Conclusion

In this tutorial, you've successfully connected a .NET application to a Google Cloud MySQL instance and completed basic CRUD operations. With this knowledge, you're equipped to build more robust cloud-native apps that leverage MySQL's flexibility within the Google Cloud ecosystem.

FAQ

How do you install and activate dotConnect for MySQL in a .NET project?
Install dotConnect for MySQL via the EXE installer or by adding the Devart.Data.MySql NuGet package to your project, then obtain your personal activation key from your Devart Customer Portal and include it in the connection string via the License key parameter for a working connection.
How do you create a connection to MySQL using dotConnect in C#?
Define a connection string that includes host, user ID, password, database, and the License key value, then create a MySqlConnection instance with this string and call Open() for it inside a try-catch block to test and handle connection errors.
How do you enable SSL/TLS for secure MySQL connections with dotConnect?
Add Protocol=SSL and specify the SSL CA Cert, SSL Cert, and SSL Key file paths in the connection string, then open the MySqlConnection connection to establish an encrypted SSL/TLS connection.
Can you connect to MySQL using Entity Framework Core and dotConnect?
Yes, you can either use Entity Developer to visually create an EF Core model from the database or run Scaffold-DbContext with a dotConnect connection string (including the License key) to generate the DbContext and entity classes.
Is it possible to connect to MySQL using Visual Studio Server Explorer with dotConnect?
Yes, in Visual Studio Server Explorer, you add a new Data Connection, choose dotConnect for MySQL as the data provider, enter your MySQL server credentials, test the connection, and then browse and manage data directly from 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 MySQL

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

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