Testcontainers JDBC driver that provides lightweight, throwaway database instances for testing
The JdbcDatabaseContainer class provides the foundation for database containers that expose JDBC connectivity with automatic lifecycle management and initialization support.
Base class for all database containers that provide JDBC connections.
/**
* Base class for containers that expose a JDBC connection
* @param <SELF> self-referencing type for fluent interface
*/
public abstract class JdbcDatabaseContainer<SELF extends JdbcDatabaseContainer<SELF>>
extends GenericContainer<SELF>
implements LinkableContainer {
}Abstract methods that database-specific implementations must provide.
/**
* Get the name of the actual JDBC driver to use
* @return fully qualified driver class name (e.g., "com.mysql.cj.jdbc.Driver")
*/
public abstract String getDriverClassName();
/**
* Get JDBC URL for connecting to the containerized database
* @return JDBC URL with container's host and port
*/
public abstract String getJdbcUrl();
/**
* Get the standard database username for connections
* @return database username
*/
public abstract String getUsername();
/**
* Get the standard password for connections
* @return database password
*/
public abstract String getPassword();
/**
* Get test query string for health checks
* @return SQL query suitable for testing database connectivity
*/
protected abstract String getTestQueryString();Methods for configuring database connection parameters.
/**
* Get the database name (may not be supported by all databases)
* @return database name
* @throws UnsupportedOperationException if not supported
*/
public String getDatabaseName();
/**
* Set the database username
* @param username database username
* @return self for method chaining
* @throws UnsupportedOperationException if not supported by database type
*/
public SELF withUsername(String username);
/**
* Set the database password
* @param password database password
* @return self for method chaining
* @throws UnsupportedOperationException if not supported by database type
*/
public SELF withPassword(String password);
/**
* Set the database name
* @param dbName database name
* @return self for method chaining
* @throws UnsupportedOperationException if not supported by database type
*/
public SELF withDatabaseName(String dbName);
/**
* Add URL parameter to JDBC connection string
* @param paramName parameter name
* @param paramValue parameter value
* @return self for method chaining
*/
public SELF withUrlParam(String paramName, String paramValue);Usage Example:
// Configure MySQL container
MySQLContainer<?> mysql = new MySQLContainer<>("mysql:8.0")
.withUsername("testuser")
.withPassword("testpass")
.withDatabaseName("testdb")
.withUrlParam("useSSL", "false")
.withUrlParam("allowPublicKeyRetrieval", "true");Methods for configuring startup and connection timeouts.
/**
* Set startup timeout including image pull time
* @param startupTimeoutSeconds timeout in seconds (default: 120)
* @return self for method chaining
*/
public SELF withStartupTimeoutSeconds(int startupTimeoutSeconds);
/**
* Set connection establishment timeout
* @param connectTimeoutSeconds timeout in seconds (default: 120)
* @return self for method chaining
*/
public SELF withConnectTimeoutSeconds(int connectTimeoutSeconds);Methods for setting up database initialization scripts and functions.
/**
* Set single initialization script (replaces any previous scripts)
* @param initScriptPath path to script file (classpath resource)
* @return self for method chaining
*/
public SELF withInitScript(String initScriptPath);
/**
* Set multiple initialization scripts in execution order
* @param initScriptPaths array of script paths
* @return self for method chaining
*/
public SELF withInitScripts(String... initScriptPaths);
/**
* Set initialization scripts from collection
* @param initScriptPaths iterable of script paths
* @return self for method chaining
*/
public SELF withInitScripts(Iterable<String> initScriptPaths);Usage Example:
PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:13")
.withInitScript("schema.sql") // Single script
.withInitScripts("001-schema.sql", "002-data.sql", "003-indexes.sql"); // Multiple scriptsMethods for obtaining and managing the underlying JDBC driver.
/**
* Get instance of the database-specific JDBC driver
* @return JDBC Driver instance
* @throws NoDriverFoundException if driver class cannot be loaded
*/
public Driver getJdbcDriverInstance() throws NoDriverFoundException;Methods for creating database connections to the containerized database.
/**
* Create connection to the database with query string parameters
* @param queryString query parameters to append (must include leading '?')
* @return database Connection
* @throws SQLException if connection cannot be established
* @throws NoDriverFoundException if JDBC driver not available
*/
public Connection createConnection(String queryString)
throws SQLException, NoDriverFoundException;
/**
* Create connection with query string and additional properties
* @param queryString query parameters to append (must include leading '?')
* @param info additional JDBC connection properties
* @return database Connection
* @throws SQLException if connection cannot be established
* @throws NoDriverFoundException if JDBC driver not available
*/
public Connection createConnection(String queryString, Properties info)
throws SQLException, NoDriverFoundException;Usage Example:
JdbcDatabaseContainer<?> container = new MySQLContainer<>("mysql:8.0");
container.start();
// Simple connection
Connection conn1 = container.createConnection("");
// Connection with parameters
Connection conn2 = container.createConnection("?useSSL=false&allowPublicKeyRetrieval=true");
// Connection with properties
Properties props = new Properties();
props.setProperty("user", "admin");
props.setProperty("password", "secret");
Connection conn3 = container.createConnection("", props);Methods for setting container-specific parameters.
/**
* Set all container parameters (replaces existing parameters)
* @param parameters map of parameter names to values
*/
public void setParameters(Map<String, String> parameters);
/**
* Add single container parameter
* @param paramName parameter name
* @param value parameter value
*/
public void addParameter(String paramName, String value);Protected method for building JDBC connection URLs.
/**
* Construct JDBC URL for connections including query parameters
* @param queryString query parameters (must start with '?')
* @return complete JDBC URL
* @throws IllegalArgumentException if queryString doesn't start with '?'
*/
protected String constructUrlForConnection(String queryString);
/**
* Construct URL parameter string with delimiters
* @param startCharacter delimiter before parameters
* @param delimiter delimiter between parameters
* @return formatted parameter string
*/
protected String constructUrlParameters(String startCharacter, String delimiter);
/**
* Construct URL parameter string with start and end delimiters
* @param startCharacter delimiter before parameters
* @param delimiter delimiter between parameters
* @param endCharacter delimiter after parameters
* @return formatted parameter string
*/
protected String constructUrlParameters(String startCharacter, String delimiter, String endCharacter);Protected methods for mapping classpath resources as container volumes.
/**
* Map classpath resource as container volume if parameter is set
* @param paramName parameter name to check
* @param pathNameInContainer target path inside container
* @param defaultResource default resource path if parameter not set
* @param fileMode optional file permissions mode
*/
protected void optionallyMapResourceParameterAsVolume(
String paramName,
String pathNameInContainer,
String defaultResource,
Integer fileMode
);Method for obtaining a database delegate for script execution.
/**
* Get database delegate for executing SQL scripts and statements
* @return DatabaseDelegate instance for this container
*/
protected DatabaseDelegate getDatabaseDelegate();Legacy methods maintained for backward compatibility.
/**
* Get startup timeout in seconds
* @return startup timeout in seconds
* @deprecated Use withStartupTimeoutSeconds() in constructor instead
*/
@Deprecated
protected int getStartupTimeoutSeconds();
/**
* Get connection timeout in seconds
* @return connection timeout in seconds
* @deprecated Use withConnectTimeoutSeconds() in constructor instead
*/
@Deprecated
protected int getConnectTimeoutSeconds();
/**
* Map classpath resource as container volume (legacy 3-parameter version)
* @param paramName parameter name to check
* @param pathNameInContainer target path inside container
* @param defaultResource default resource path if parameter not set
* @deprecated Use 4-parameter version with fileMode instead
*/
@Deprecated
protected void optionallyMapResourceParameterAsVolume(
String paramName,
String pathNameInContainer,
String defaultResource
);Available constructors for creating container instances.
/**
* Create container with Docker image name string
* @param dockerImageName Docker image name
* @deprecated Use DockerImageName version instead
*/
public JdbcDatabaseContainer(String dockerImageName);
/**
* Create container with future image name
* @param image Future that will resolve to image name
*/
public JdbcDatabaseContainer(Future<String> image);
/**
* Create container with DockerImageName
* @param dockerImageName Docker image name object
*/
public JdbcDatabaseContainer(DockerImageName dockerImageName);/**
* Exception thrown when JDBC driver cannot be found or loaded
*/
public static class NoDriverFoundException extends RuntimeException {
public NoDriverFoundException(String message, Throwable cause);
}The container follows standard Testcontainers lifecycle:
withUsername(), withInitScript() configure the containerstart() called or first connection requestedstop() called or test completesWhen initialization scripts are provided:
Script Execution Options:
Install with Tessl CLI
npx tessl i tessl/maven-org-testcontainers--jdbc