or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdconnections.mddata-sources.mddata-types.mdhigh-availability.mdindex.mdpooling.mdsecurity.mdstatements.md

connections.mddocs/

0

# Database Connections

1

2

Core connection functionality for establishing and managing database connections with comprehensive configuration options, SSL/TLS security, and multi-host support.

3

4

## Capabilities

5

6

### Driver Registration and Connection

7

8

The main JDBC Driver class for connecting to MariaDB and MySQL databases.

9

10

```java { .api }

11

/**

12

* MariaDB JDBC Driver implementation

13

*/

14

public final class Driver implements java.sql.Driver {

15

/**

16

* Connect to database using JDBC URL and properties

17

* @param url JDBC connection URL

18

* @param props Connection properties

19

* @return Connection to the database

20

* @throws SQLException if connection fails

21

*/

22

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

23

24

/**

25

* Connect using a Configuration object

26

* @param configuration Pre-built configuration

27

* @return Connection to the database

28

* @throws SQLException if connection fails

29

*/

30

public static Connection connect(Configuration configuration) throws SQLException;

31

32

/**

33

* Check if driver accepts the given URL

34

* @param url JDBC URL to validate

35

* @return true if URL is acceptable

36

* @throws SQLException if URL validation fails

37

*/

38

public boolean acceptsURL(String url) throws SQLException;

39

40

/**

41

* Get configuration properties information

42

* @param url JDBC URL

43

* @param info Current properties

44

* @return Array of property information

45

* @throws SQLException if property retrieval fails

46

*/

47

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

48

49

/**

50

* Quote SQL identifier for safe use in queries

51

* @param identifier Identifier to quote

52

* @param alwaysQuote Force quoting even if not needed

53

* @return Quoted identifier

54

*/

55

public static String enquoteIdentifier(String identifier, boolean alwaysQuote);

56

57

/**

58

* Quote SQL string literal for safe use in queries

59

* @param val String value to quote

60

* @return Quoted string literal

61

*/

62

public static String enquoteLiteral(String val);

63

64

/**

65

* Check if identifier is simple (no special characters)

66

* @param identifier Identifier to check

67

* @return true if identifier is simple

68

*/

69

public static boolean isSimpleIdentifier(String identifier);

70

}

71

```

72

73

**Usage Examples:**

74

75

```java

76

// Basic connection using DriverManager

77

String url = "jdbc:mariadb://localhost:3306/mydb";

78

Properties props = new Properties();

79

props.setProperty("user", "myuser");

80

props.setProperty("password", "mypass");

81

Connection conn = DriverManager.getConnection(url, props);

82

83

// Connection with SSL

84

String sslUrl = "jdbc:mariadb://localhost:3306/mydb?sslMode=VERIFY_FULL&serverSslCert=/path/to/cert.pem";

85

Connection secureConn = DriverManager.getConnection(sslUrl, "user", "pass");

86

87

// Quote identifiers and literals safely

88

String quotedTable = Driver.enquoteIdentifier("my table", true); // "`my table`"

89

String quotedValue = Driver.enquoteLiteral("O'Brien"); // "'O\\'Brien'"

90

```

91

92

### Connection Implementation

93

94

MariaDB's Connection implementation with standard JDBC functionality plus driver-specific extensions.

95

96

```java { .api }

97

/**

98

* MariaDB Connection implementation

99

*/

100

public class Connection implements java.sql.Connection {

101

/**

102

* Cancel the currently executing query (MariaDB-specific)

103

* @throws SQLException if cancellation fails

104

*/

105

public void cancelCurrentQuery() throws SQLException;

106

107

// Standard JDBC Connection methods

108

public Statement createStatement() throws SQLException;

109

public PreparedStatement prepareStatement(String sql) throws SQLException;

110

public CallableStatement prepareCall(String sql) throws SQLException;

111

public DatabaseMetaData getMetaData() throws SQLException;

112

public void setAutoCommit(boolean autoCommit) throws SQLException;

113

public boolean getAutoCommit() throws SQLException;

114

public void commit() throws SQLException;

115

public void rollback() throws SQLException;

116

public void close() throws SQLException;

117

public boolean isClosed() throws SQLException;

118

public void setTransactionIsolation(int level) throws SQLException;

119

public int getTransactionIsolation() throws SQLException;

120

}

121

```

122

123

**Usage Examples:**

124

125

```java

126

// Create different statement types

127

Connection conn = DriverManager.getConnection(url, user, pass);

128

129

// Simple statement

130

Statement stmt = conn.createStatement();

131

ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM users");

132

133

// Prepared statement with parameters

134

PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE age > ? AND city = ?");

135

pstmt.setInt(1, 25);

136

pstmt.setString(2, "New York");

137

ResultSet prs = pstmt.executeQuery();

138

139

// Callable statement for stored procedures

140

CallableStatement cstmt = conn.prepareCall("{call getUserStats(?, ?)}");

141

cstmt.setInt(1, 100);

142

cstmt.registerOutParameter(2, Types.INTEGER);

143

cstmt.execute();

144

int count = cstmt.getInt(2);

145

146

// Transaction management

147

conn.setAutoCommit(false);

148

try {

149

// Execute multiple operations

150

stmt.executeUpdate("INSERT INTO orders (user_id, amount) VALUES (1, 100.00)");

151

stmt.executeUpdate("UPDATE users SET balance = balance - 100 WHERE id = 1");

152

conn.commit();

153

} catch (SQLException e) {

154

conn.rollback();

155

throw e;

156

}

157

158

// Cancel long-running query (MariaDB-specific feature)

159

// In another thread:

160

conn.cancelCurrentQuery();

161

```

162

163

### Connection URL Format

164

165

Standard JDBC URL format with MariaDB-specific extensions for high availability and advanced configuration.

166

167

**Basic Format:**

168

```

169

jdbc:mariadb://host:port/database?option1=value1&option2=value2

170

```

171

172

**High Availability Format:**

173

```

174

jdbc:mariadb:replication://primary:3306,replica:3306/database

175

jdbc:mariadb:loadbalance://host1:3306,host2:3306,host3:3306/database

176

```

177

178

**Advanced Host Format:**

179

```

180

jdbc:mariadb://address=(host=server1)(port=3306)(type=primary),address=(host=server2)(port=3306)(type=replica)/database

181

```

182

183

**Special Connection Types:**

184

```

185

jdbc:mariadb://address=(pipe=\\\\.\\pipe\\mysql)/database // Windows named pipe

186

jdbc:mariadb://address=(localSocket=/var/run/mysqld/mysqld.sock)/database // Unix socket

187

```

188

189

**Common Configuration Examples:**

190

191

```java

192

// SSL connection

193

String sslUrl = "jdbc:mariadb://localhost:3306/mydb?sslMode=VERIFY_FULL&trustStore=/path/to/truststore.jks";

194

195

// Connection pooling

196

String poolUrl = "jdbc:mariadb://localhost:3306/mydb?pool=true&maxPoolSize=20&minPoolSize=5";

197

198

// High availability with failover

199

String haUrl = "jdbc:mariadb:replication://primary:3306,replica1:3306,replica2:3306/mydb?retriesAllDown=3";

200

201

// Performance tuning

202

String perfUrl = "jdbc:mariadb://localhost:3306/mydb?useCompression=true&cachePrepStmts=true&prepStmtCacheSize=250";

203

204

// Authentication

205

String authUrl = "jdbc:mariadb://localhost:3306/mydb?credentialType=ENV&restrictedAuth=mysql_native_password";

206

```

207

208

### Host Address Configuration

209

210

Utility class for managing database host addresses and connection endpoints.

211

212

```java { .api }

213

/**

214

* Database host address configuration

215

*/

216

public class HostAddress {

217

/**

218

* Create host address for standard TCP connection

219

* @param host Hostname or IP address

220

* @param port Port number

221

* @return HostAddress instance

222

*/

223

public static HostAddress from(String host, int port);

224

225

/**

226

* Create host address with primary/replica designation

227

* @param host Hostname or IP address

228

* @param port Port number

229

* @param primary true if primary server, false if replica

230

* @return HostAddress instance

231

*/

232

public static HostAddress from(String host, int port, boolean primary);

233

234

/**

235

* Create host address for Windows named pipe

236

* @param pipe Named pipe path

237

* @return HostAddress instance for pipe connection

238

*/

239

public static HostAddress pipe(String pipe);

240

241

/**

242

* Create host address for Unix domain socket

243

* @param localSocket Unix socket path

244

* @return HostAddress instance for socket connection

245

*/

246

public static HostAddress localSocket(String localSocket);

247

248

/**

249

* Parse connection string into host addresses

250

* @param spec Connection specification string

251

* @param haMode High availability mode

252

* @return List of parsed host addresses

253

*/

254

public static List<HostAddress> parse(String spec, HaMode haMode);

255

256

// Connection tracking methods

257

public Long getThreadConnectedTimeout();

258

public int getThreadsConnected();

259

}

260

```

261

262

**Usage Examples:**

263

264

```java

265

// Create host addresses programmatically

266

HostAddress primary = HostAddress.from("db-primary", 3306, true);

267

HostAddress replica1 = HostAddress.from("db-replica-1", 3306, false);

268

HostAddress replica2 = HostAddress.from("db-replica-2", 3306, false);

269

270

// Special connection types

271

HostAddress pipeAddr = HostAddress.pipe("\\\\.\\pipe\\mysql");

272

HostAddress socketAddr = HostAddress.localSocket("/var/run/mysqld/mysqld.sock");

273

274

// Parse connection string

275

List<HostAddress> hosts = HostAddress.parse(

276

"primary:3306,replica1:3306,replica2:3306",

277

HaMode.REPLICATION

278

);

279

```

280

281

## Connection Lifecycle

282

283

```java

284

// Standard connection lifecycle

285

Connection conn = null;

286

try {

287

// Establish connection

288

conn = DriverManager.getConnection(url, user, password);

289

290

// Use connection

291

Statement stmt = conn.createStatement();

292

ResultSet rs = stmt.executeQuery("SELECT * FROM table");

293

294

// Process results

295

while (rs.next()) {

296

// Process row

297

}

298

299

} catch (SQLException e) {

300

// Handle exceptions

301

e.printStackTrace();

302

} finally {

303

// Always close connection

304

if (conn != null && !conn.isClosed()) {

305

conn.close();

306

}

307

}

308

309

// Try-with-resources (recommended)

310

try (Connection conn = DriverManager.getConnection(url, user, password);

311

Statement stmt = conn.createStatement();

312

ResultSet rs = stmt.executeQuery("SELECT * FROM table")) {

313

314

while (rs.next()) {

315

// Process row

316

}

317

} catch (SQLException e) {

318

e.printStackTrace();

319

}

320

```