JDBC

Apps Script는 다음을 통해 외부 데이터베이스에 연결할 수 있습니다. JDBC 서비스는 표준 자바 애플리케이션을 둘러싼 래퍼입니다. Java Database Connectivity 기술. JDBC 서비스는 MySQL용 Google Cloud SQL, MySQL, Microsoft SQL을 지원합니다. 서버 및 Oracle 데이터베이스입니다.

외부 데이터베이스를 JDBC로 업데이트하려면 스크립트에서 연결을 열어야 합니다. SQL 문을 전송하여 변경합니다.

Google Cloud SQL 데이터베이스

Google Cloud SQL은 Google Cloud에서 제공하는 Google의 클라우드 기반 서비스입니다 Cloud SQL은 사용량에 따라 요금이 부과될 수 있습니다.

다음 목록에 나열된 단계에 따라 Google Cloud SQL 인스턴스를 만들 수 있습니다. Cloud SQL 빠른 시작

Google Cloud SQL 연결 만들기

Google Cloud SQL과 연결을 설정하는 방법에는 두 가지가 있습니다. JDBC 서비스를 사용하여 데이터베이스를 데이터베이스에 저장할 수 있습니다.

이러한 메서드는 아래에 설명되어 있습니다. 둘 다 유효하지만 두 번째 방법은 데이터베이스에 액세스할 수 있도록 IP 범위 집합을 승인해야 합니다.

이 메서드는 Jdbc.getCloudSqlConnection(url)을 사용하여 Google Cloud SQL MySQL 인스턴스에 대한 연결을 만듭니다. 메서드를 사용하여 축소하도록 요청합니다. 데이터베이스 URL은 jdbc:google:mysql://subname 형식입니다. 여기서 subname은 MySQL 인스턴스 연결 이름입니다. Cloud SQL 인스턴스 개요 페이지의 Google Cloud 콘솔.

Cloud SQL SQL Server에 연결하려면 Jdbc.getConnection(url)을 참조하세요.

Jdbc.getConnection(url) 사용

이 방법을 사용하려면 클래스 없는 도메인 간 라우팅 (CIDR) Apps Script 서버가 데이터베이스에 연결할 수 있도록 IP 주소 범위를 지정합니다. 스크립트를 실행하기 전에 다음 단계를 완료하세요.

  1. Google Cloud SQL 인스턴스에서 IP 범위를 승인하고 하나씩 이 데이터 소스에서 하나씩 가져올 수 있습니다.

  2. 데이터베이스에 할당된 URL을 복사합니다. 첫 번째 레이어에 양식 jdbc:mysql:subname.

이 IP 범위를 승인하면 Google Cloud SQL 인스턴스에 Jdbc.getConnection(url) 메서드 및 위에서 복사한 URL이 표시됩니다.

기타 데이터베이스

이미 MySQL, Microsoft SQL Server 또는 Oracle 데이터베이스가 있다면 Apps Script의 JDBC 서비스를 통해 연결할 수 있습니다.

다른 데이터베이스 연결 만들기

Apps Script를 사용하여 데이터베이스 연결을 만들기 위해 JDBC 서비스 - 데이터베이스 설정에 있음 이 데이터 소스의 IP 범위를 승인해야 합니다.

이러한 허용 목록이 준비되면 데이터베이스에 대한 연결을 만들 수 있습니다. 다음 중 하나를 사용하여 Jdbc.getConnection(url) 메서드 및 데이터베이스 URL이 필요합니다.

샘플 코드

아래 샘플 코드는 Google Cloud SQL 데이터베이스에 연결한다고 가정합니다. 를 사용하여 데이터베이스 연결을 생성합니다. Jdbc.getCloudSqlConnection(url) 메서드를 사용하여 축소하도록 요청합니다. 다른 데이터베이스의 경우 Jdbc.getConnection(url) 메서드를 사용하여 데이터베이스 연결을 생성합니다.

JDBC 메서드에 대한 자세한 내용은 JDBC에 대한 자바 문서

데이터베이스, 사용자, 테이블 만들기

대부분의 개발자는 MySQL 명령줄 도구를 사용하여 데이터베이스, 사용자, 테이블을 만들 수 있습니다. 같은 작업을 할 수도 있습니다. 애플리케이션 스크립트에 있습니다. 최소 한 개 이상의 따라서 스크립트가 항상 데이터베이스에 root

service/jdbc.gs
/**
 * Create a new database within a Cloud SQL instance.
 */
function createDatabase() {
  try {
    const conn = Jdbc.getCloudSqlConnection(instanceUrl, root, rootPwd);
    conn.createStatement().execute('CREATE DATABASE ' + db);
  } catch (err) {
    // TODO(developer) - Handle exception from the API
    console.log('Failed with an error %s', err.message);
  }
}

/**
 * Create a new user for your database with full privileges.
 */
function createUser() {
  try {
    const conn = Jdbc.getCloudSqlConnection(dbUrl, root, rootPwd);

    const stmt = conn.prepareStatement('CREATE USER ? IDENTIFIED BY ?');
    stmt.setString(1, user);
    stmt.setString(2, userPwd);
    stmt.execute();

    conn.createStatement().execute('GRANT ALL ON `%`.* TO ' + user);
  } catch (err) {
    // TODO(developer) - Handle exception from the API
    console.log('Failed with an error %s', err.message);
  }
}

/**
 * Create a new table in the database.
 */
function createTable() {
  try {
    const conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);
    conn.createStatement().execute('CREATE TABLE entries ' +
      '(guestName VARCHAR(255), content VARCHAR(255), ' +
      'entryID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(entryID));');
  } catch (err) {
    // TODO(developer) - Handle exception from the API
    console.log('Failed with an error %s', err.message);
  }
}

데이터베이스에 쓰기

아래 예는 데이터베이스에 단일 레코드를 다음과 같이 쓰는 방법을 보여줍니다. 500개 레코드의 배치로 구성됩니다. 일괄 처리는 일괄 작업에 매우 중요합니다.

또한 ?로 표시됩니다. SQL 삽입 공격의 경우 문을 사용하여 사용자가 제공한 모든 데이터를 이스케이프 처리하세요.

service/jdbc.gs
/**
 * Write one row of data to a table.
 */
function writeOneRecord() {
  try {
    const conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);

    const stmt = conn.prepareStatement('INSERT INTO entries ' +
      '(guestName, content) values (?, ?)');
    stmt.setString(1, 'First Guest');
    stmt.setString(2, 'Hello, world');
    stmt.execute();
  } catch (err) {
    // TODO(developer) - Handle exception from the API
    console.log('Failed with an error %s', err.message);
  }
}

/**
 * Write 500 rows of data to a table in a single batch.
 */
function writeManyRecords() {
  try {
    const conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);
    conn.setAutoCommit(false);

    const start = new Date();
    const stmt = conn.prepareStatement('INSERT INTO entries ' +
      '(guestName, content) values (?, ?)');
    for (let i = 0; i < 500; i++) {
      stmt.setString(1, 'Name ' + i);
      stmt.setString(2, 'Hello, world ' + i);
      stmt.addBatch();
    }

    const batch = stmt.executeBatch();
    conn.commit();
    conn.close();

    const end = new Date();
    console.log('Time elapsed: %sms for %s rows.', end - start, batch.length);
  } catch (err) {
    // TODO(developer) - Handle exception from the API
    console.log('Failed with an error %s', err.message);
  }
}

데이터베이스에서 읽기

이 예는 필요에 따라 결과 집합을 반복하는 것입니다.

service/jdbc.gs
/**
 * Read up to 1000 rows of data from the table and log them.
 */
function readFromTable() {
  try {
    const conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);
    const start = new Date();
    const stmt = conn.createStatement();
    stmt.setMaxRows(1000);
    const results = stmt.executeQuery('SELECT * FROM entries');
    const numCols = results.getMetaData().getColumnCount();

    while (results.next()) {
      let rowString = '';
      for (let col = 0; col < numCols; col++) {
        rowString += results.getString(col + 1) + '\t';
      }
      console.log(rowString);
    }

    results.close();
    stmt.close();

    const end = new Date();
    console.log('Time elapsed: %sms', end - start);
  } catch (err) {
    // TODO(developer) - Handle exception from the API
    console.log('Failed with an error %s', err.message);
  }
}

연결 닫기

스크립트 실행이 완료되면 JDBC 연결이 자동으로 종료됩니다. (유지 하나의 google.script.run가 호출은 완전한 실행으로 계산됩니다. 이는 통화가 열린 상태로 유지됩니다.)

그럼에도 불구하고 연결, 문 또는 결과 집합을 마쳤다는 것을 알고 있다면 스크립트가 끝나기 전에 JdbcConnection.close()님, JdbcStatement.close(), 또는 JdbcResultSet.close():

알림 또는 프롬프트 대화상자 표시 열려 있는 JDBC 연결도 종료합니다. 하지만 다른 표시 UI는 요소(예: 맞춤 메뉴, 맞춤 메뉴 또는 맞춤 기능이 있는 콘텐츠가 포함되지 않습니다.

Google, Google Workspace 및 관련 마크와 로고는 Google LLC. 기타 모든 회사명 및 제품명은 관련되어 있습니다.