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.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample


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