MySQL Servlet 連線

使用 HikariCP JDBC 連線集區程式庫,執行 SQL INSERT 陳述式,開啟及關閉與 MySQL 適用的 Cloud SQL 連線。

深入探索

如需包含此程式碼範例的詳細說明文件,請參閱以下文件:

程式碼範例

Java

如要驗證 MySQL 適用的 Cloud SQL,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證機制」。

// Using a try-with-resources statement ensures that the connection is always released back
// into the pool at the end of the statement (even if an error occurs)
try (Connection conn = pool.getConnection()) {

  // PreparedStatements can be more efficient and project against injections.
  String stmt = "INSERT INTO votes (time_cast, candidate) VALUES (?, ?);";
  try (PreparedStatement voteStmt = conn.prepareStatement(stmt);) {
    voteStmt.setTimestamp(1, now);
    voteStmt.setString(2, team);

    // Finally, execute the statement. If it fails, an error will be thrown.
    voteStmt.execute();
  }
} catch (SQLException ex) {
  // If something goes wrong, handle the error in this section. This might involve retrying or
  // adjusting parameters depending on the situation.
  // ...
}

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱 Google Cloud 範例瀏覽器