Create connection (v2)

Create a new connection to a Cloud SQL database.

Code sample

Java

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.CloudSqlIamCredential;
import com.google.privacy.dlp.v2.CloudSqlProperties;
import com.google.privacy.dlp.v2.CloudSqlProperties.DatabaseEngine;
import com.google.privacy.dlp.v2.Connection;
import com.google.privacy.dlp.v2.ConnectionState;
import com.google.privacy.dlp.v2.CreateConnectionRequest;
import java.io.IOException;

public class CreateConnection {

  public static void main(String[] args) throws IOException {
    String projectId = "example-project-id";
    String locationId = "example-location-id";
    createConnection(projectId, locationId);
  }

  public static void createConnection(String projectId, String locationId) throws IOException {
    try (DlpServiceClient client = DlpServiceClient.create()) {
      String parent = String.format("projects/%s/locations/%s", projectId, locationId);

      CloudSqlProperties cloudSql =
          CloudSqlProperties.newBuilder()
              .setConnectionName(String.format("%s:%s:example-instance", projectId, locationId))
              .setDatabaseEngine(DatabaseEngine.DATABASE_ENGINE_MYSQL)
              .setMaxConnections(2)
              .setCloudSqlIam(CloudSqlIamCredential.getDefaultInstance())
              .build();

      Connection connection =
          Connection.newBuilder()
              .setState(ConnectionState.AVAILABLE)
              .setCloudSql(cloudSql)
              .build();

      CreateConnectionRequest request =
          CreateConnectionRequest.newBuilder()
              .setParent(parent)
              .setConnection(connection)
              .build();

      Connection response = client.createConnection(request);
      System.out.println("Created connection: " + response.getName());
    }
  }
}

Node.js

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

'use strict';

const {DlpServiceClient} = require('@google-cloud/dlp');
const {status} = require('@grpc/grpc-js');

const client = new DlpServiceClient();

/**
 * Creates a connection in Sensitive Data Protection.
 *
 * @param {string} projectId - The Google Cloud project ID (for example, 'example-project-id')
 * @param {string} locationId - The Google Cloud region where the service is located (for example, 'us-central1')
 */
async function createConnection(projectId, locationId) {
  try {
    const parent = `projects/${projectId}/locations/${locationId}`;

    const cloudSql = {
      connectionName: `${projectId}:${locationId}:example-instance`,
      databaseEngine: 'DATABASE_ENGINE_MYSQL',
      maxConnections: 2,
      cloudSqlIam: {},
    };

    const connection = {
      state: 'AVAILABLE',
      cloudSql,
    };

    const request = {
      parent,
      connection,
    };

    const [response] = await client.createConnection(request);
    console.log(`Connection created: ${response.name}`);
    return response;
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Connection already exists: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else if (err.code !== undefined) {
      console.error(`Service error [${err.code}]: ${err.message}`);
    } else {
      console.error(`Unexpected error: ${err.message}`);
    }
    throw err;
  }
}

module.exports = {createConnection};

Python

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import google.api_core.exceptions
from google.cloud import dlp_v2

client = dlp_v2.DlpServiceClient()


def create_connection(project_id: str, location_id: str) -> None:
    """Create a Cloud Data Loss Prevention connection for Cloud SQL.

    Args:
        project_id: The Google Cloud project ID under which to create the connection.
        location_id: The Google Cloud region where the connection is created (for example, 'us-central1').
    """
    parent = f"projects/{project_id}/locations/{location_id}"

    cloud_sql_properties = dlp_v2.CloudSqlProperties(
        connection_name=f"{project_id}:{location_id}:sample-instance",
        database_engine=dlp_v2.CloudSqlProperties.DatabaseEngine.DATABASE_ENGINE_POSTGRES,
        max_connections=5,
        cloud_sql_iam=dlp_v2.CloudSqlIamCredential(),
    )

    connection = dlp_v2.Connection(
        state=dlp_v2.ConnectionState.AVAILABLE,
        cloud_sql=cloud_sql_properties,
    )

    try:
        response = client.create_connection(
            parent=parent,
            connection=connection,
        )
        print(f"Created connection: {response.name}")
    except google.api_core.exceptions.GoogleAPICallError as e:
        print(f"API call failed: {e}")

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.