MySQL servlet connection

Run a SQL INSERT statement to open and close a connection to Cloud SQL for MySQL by using the HikariCP JDBC connection pool library.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

Java

To authenticate to Cloud SQL for MySQL, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// 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.
  // ...
}

What's next

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