How to connect Google Cloud SQL with C#

2019-01-29 13:05发布

问题:

I just want to manage my database on Google Cloud using C#. I have just started learning database. P.S. I am not good at English. I hope you understand me.

回答1:

I assume you've already created your Google Cloud SQL MySQL instance.

Following the instructions at Connect to your Cloud SQL instance using SSL, you'll need to enable external SSL access and create a client certificate.

You'll download the three files: server-ca.pem, client-cert.pem, client-key.pem.

Following these instructions, convert client-cert.pem and client-key.pem to a pfx file:

openssl pkcs12 -inkey client-key.pem -in client-cert.pem -export -out client.pfx

Install the MySqlConnector NuGet package into your C# application.

Create your connection string as follows:

var csb = new MySqlConnectionStringBuilder
{
    Server = "Google Cloud SQL IP address",
    UserID = "Your UserName",
    Password = "Your Password",
    Database = "Your Database/Schema Name",
    CertificateFile = @"C:\Path\To\client.pfx",
    CACertificateFile = @"C:\Path\To\server-ca.pem",
    SslMode = MySqlSslMode.VerifyCA,
};
using (var connection = new MySqlConnection(csb.ConnectionString))
{
    connection.Open();
}