MySQL servlet connection

Stay organized with collections Save and categorize content based on your preferences.

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


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