or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

container-providers.mddatabase-containers.mdindex.mdjdbc-driver.mdurl-configuration.md

index.mddocs/

0

# Testcontainers JDBC

1

2

Testcontainers JDBC provides a JDBC driver proxy that automatically provisions Docker containers running database engines for testing purposes. It handles JDBC URLs with the 'jdbc:tc:' prefix, automatically launching appropriate database containers and routing connections to them, enabling developers to write integration tests against real database instances in isolated, reproducible environments.

3

4

## Package Information

5

6

- **Package Name**: org.testcontainers:jdbc

7

- **Package Type**: maven

8

- **Language**: Java

9

- **Installation**:

10

```xml

11

<dependency>

12

<groupId>org.testcontainers</groupId>

13

<artifactId>jdbc</artifactId>

14

<version>1.21.3</version>

15

</dependency>

16

```

17

18

## Core Imports

19

20

```java

21

import org.testcontainers.jdbc.ContainerDatabaseDriver;

22

import org.testcontainers.containers.JdbcDatabaseContainer;

23

import org.testcontainers.containers.JdbcDatabaseContainerProvider;

24

import org.testcontainers.jdbc.ConnectionUrl;

25

import org.testcontainers.jdbc.JdbcDatabaseDelegate;

26

import org.testcontainers.jdbc.ConnectionWrapper;

27

```

28

29

## Basic Usage

30

31

```java

32

import java.sql.Connection;

33

import java.sql.DriverManager;

34

import java.sql.SQLException;

35

36

public class DatabaseTest {

37

public void testWithJdbcUrl() throws SQLException {

38

// The JDBC URL automatically provisions a MySQL container

39

String jdbcUrl = "jdbc:tc:mysql:8.0.33://localhost/testdb?TC_INITSCRIPT=init.sql";

40

41

try (Connection connection = DriverManager.getConnection(jdbcUrl)) {

42

// Use the connection - container is automatically managed

43

// Container will be stopped when all connections are closed

44

}

45

}

46

}

47

```

48

49

## Architecture

50

51

Testcontainers JDBC is built around several key components:

52

53

- **Driver Proxy**: `ContainerDatabaseDriver` intercepts JDBC connections and manages container lifecycle

54

- **Container Abstraction**: `JdbcDatabaseContainer` provides database-agnostic container operations

55

- **Provider System**: Service loader pattern with `JdbcDatabaseContainerProvider` for database-specific implementations

56

- **URL Parsing**: `ConnectionUrl` handles complex JDBC URL parsing and parameter extraction

57

- **Connection Management**: Automatic container lifecycle tied to connection usage patterns

58

- **Initialization Support**: Built-in script execution and programmatic initialization capabilities

59

60

## Capabilities

61

62

### JDBC Driver Proxy

63

64

Core JDBC driver implementation that intercepts tc: URLs and manages database containers automatically.

65

66

```java { .api }

67

public class ContainerDatabaseDriver implements java.sql.Driver {

68

public boolean acceptsURL(String url) throws SQLException;

69

public Connection connect(String url, Properties info) throws SQLException;

70

public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException;

71

public int getMajorVersion();

72

public int getMinorVersion();

73

public boolean jdbcCompliant();

74

public Logger getParentLogger() throws SQLFeatureNotSupportedException;

75

76

// Utility methods for container management

77

public static void killContainers();

78

public static void killContainer(String jdbcUrl);

79

static JdbcDatabaseContainer getContainer(String jdbcUrl);

80

}

81

```

82

83

[JDBC Driver](./jdbc-driver.md)

84

85

### Database Container Management

86

87

Abstract base class for database containers that provide JDBC connectivity with lifecycle management and initialization support.

88

89

```java { .api }

90

public abstract class JdbcDatabaseContainer<SELF extends JdbcDatabaseContainer<SELF>>

91

extends GenericContainer<SELF> implements LinkableContainer {

92

93

// Abstract methods that must be implemented

94

public abstract String getDriverClassName();

95

public abstract String getJdbcUrl();

96

public abstract String getUsername();

97

public abstract String getPassword();

98

protected abstract String getTestQueryString();

99

100

// Configuration methods

101

public SELF withUsername(String username);

102

public SELF withPassword(String password);

103

public SELF withDatabaseName(String dbName);

104

public SELF withUrlParam(String paramName, String paramValue);

105

public SELF withStartupTimeoutSeconds(int startupTimeoutSeconds);

106

public SELF withConnectTimeoutSeconds(int connectTimeoutSeconds);

107

public SELF withInitScript(String initScriptPath);

108

public SELF withInitScripts(String... initScriptPaths);

109

public SELF withInitScripts(Iterable<String> initScriptPaths);

110

111

// Connection methods

112

public Driver getJdbcDriverInstance() throws NoDriverFoundException;

113

public Connection createConnection(String queryString) throws SQLException, NoDriverFoundException;

114

public Connection createConnection(String queryString, Properties info) throws SQLException, NoDriverFoundException;

115

}

116

```

117

118

[Database Containers](./database-containers.md)

119

120

### Container Provider System

121

122

Service provider interface for creating database-specific container implementations based on JDBC URL database types.

123

124

```java { .api }

125

public abstract class JdbcDatabaseContainerProvider {

126

public abstract boolean supports(String databaseType);

127

public abstract JdbcDatabaseContainer newInstance(String tag);

128

public JdbcDatabaseContainer newInstance();

129

public JdbcDatabaseContainer newInstance(ConnectionUrl url);

130

131

protected JdbcDatabaseContainer newInstanceFromConnectionUrl(

132

ConnectionUrl connectionUrl,

133

String userParamName,

134

String pwdParamName

135

);

136

}

137

```

138

139

[Container Providers](./container-providers.md)

140

141

### URL Parsing and Configuration

142

143

Comprehensive URL parsing for JDBC connection strings with Testcontainers-specific parameters and database configuration.

144

145

```java { .api }

146

public class ConnectionUrl {

147

public static ConnectionUrl newInstance(String url);

148

public static boolean accepts(String url);

149

150

// Getters for parsed components

151

public String getUrl();

152

public String getDatabaseType();

153

public Optional<String> getImageTag();

154

public String getDbHostString();

155

public boolean isInDaemonMode();

156

public Optional<String> getDatabaseHost();

157

public Optional<Integer> getDatabasePort();

158

public Optional<String> getDatabaseName();

159

public Optional<String> getInitScriptPath();

160

public boolean isReusable();

161

public Optional<InitFunctionDef> getInitFunction();

162

public Optional<String> getQueryString();

163

public Map<String, String> getContainerParameters();

164

public Map<String, String> getQueryParameters();

165

public Map<String, String> getTmpfsOptions();

166

}

167

```

168

169

[URL Configuration](./url-configuration.md)

170

171

## Common URL Parameters

172

173

### Database Configuration

174

- Standard JDBC parameters (user, password, etc.)

175

- Database-specific options passed through to underlying driver

176

177

### Container Parameters (TC_*)

178

- `TC_INITSCRIPT` - Path to SQL initialization script (classpath or file:// resource)

179

- `TC_INITFUNCTION` - Method reference for programmatic initialization (format: `com.example.Class::method`)

180

- `TC_DAEMON` - Keep container running across multiple connection cycles

181

- `TC_REUSABLE` - Mark container for potential reuse across test runs

182

- `TC_TMPFS` - Configure tmpfs mounts for performance (format: `path:options`)

183

184

## Connection Management Classes

185

186

### Connection Wrapper

187

188

Internal connection wrapper that provides lifecycle callbacks for container cleanup.

189

190

```java { .api }

191

public class ConnectionWrapper extends ConnectionDelegate {

192

public ConnectionWrapper(Connection connection, Runnable closeCallback);

193

194

@Override

195

public void close() throws SQLException;

196

}

197

```

198

199

### Connection Delegate

200

201

Simple JDBC Connection delegate that forwards all calls to the underlying connection.

202

203

```java { .api }

204

class ConnectionDelegate implements Connection {

205

// Implements all Connection interface methods via delegation

206

}

207

```

208

209

### Database Delegates

210

211

JDBC-based database delegates for executing SQL scripts and statements.

212

213

```java { .api }

214

public class JdbcDatabaseDelegate extends AbstractDatabaseDelegate<Statement> {

215

public JdbcDatabaseDelegate(JdbcDatabaseContainer container, String queryString);

216

217

@Override

218

protected Statement createNewConnection();

219

220

@Override

221

public void execute(String statement, String scriptPath, int lineNumber,

222

boolean continueOnError, boolean ignoreFailedDrops);

223

}

224

225

/**

226

* @deprecated Used only with deprecated ScriptUtils

227

*/

228

@Deprecated

229

public class ContainerLessJdbcDelegate extends JdbcDatabaseDelegate {

230

public ContainerLessJdbcDelegate(Connection connection);

231

232

@Override

233

protected Statement createNewConnection();

234

}

235

```

236

237

## Legacy Utilities

238

239

### Deprecated Script Utilities

240

241

Legacy SQL script utilities maintained for backward compatibility.

242

243

```java { .api }

244

/**

245

* @deprecated Use database-agnostic ScriptUtils instead

246

*/

247

@Deprecated

248

public abstract class org.testcontainers.jdbc.ext.ScriptUtils {

249

public static final String DEFAULT_STATEMENT_SEPARATOR = ";";

250

public static final String FALLBACK_STATEMENT_SEPARATOR = "\n";

251

public static final String DEFAULT_COMMENT_PREFIX = "--";

252

public static final String DEFAULT_BLOCK_COMMENT_START_DELIMITER = "/*";

253

public static final String DEFAULT_BLOCK_COMMENT_END_DELIMITER = "*/";

254

255

public static void splitSqlScript(String resource, String script, String separator,

256

String commentPrefix, String blockCommentStartDelimiter,

257

String blockCommentEndDelimiter, List<String> statements);

258

public static boolean containsSqlScriptDelimiters(String script, String delim);

259

public static void executeSqlScript(Connection connection, String scriptPath, String script)

260

throws ScriptException;

261

public static void executeSqlScript(Connection connection, String scriptPath, String script,

262

boolean continueOnError, boolean ignoreFailedDrops,

263

String commentPrefix, String separator,

264

String blockCommentStartDelimiter,

265

String blockCommentEndDelimiter) throws ScriptException;

266

}

267

```

268

269

## Exception Types

270

271

```java { .api }

272

public static class NoDriverFoundException extends RuntimeException {

273

public NoDriverFoundException(String message, Throwable cause);

274

}

275

```