JDBC 4.2 compatible driver providing comprehensive database connectivity for MariaDB and MySQL servers
—
Comprehensive statement execution support including prepared statements, callable statements, batch operations, and streaming result sets.
Standard JDBC Statement implementation for executing SQL queries.
/**
* MariaDB Statement implementation
*/
public class Statement implements java.sql.Statement {
// Query execution
public ResultSet executeQuery(String sql) throws SQLException;
public int executeUpdate(String sql) throws SQLException;
public boolean execute(String sql) throws SQLException;
// Batch operations
public void addBatch(String sql) throws SQLException;
public int[] executeBatch() throws SQLException;
public void clearBatch() throws SQLException;
// Result set management
public ResultSet getResultSet() throws SQLException;
public int getUpdateCount() throws SQLException;
public boolean getMoreResults() throws SQLException;
public boolean getMoreResults(int current) throws SQLException;
// Configuration
public void setMaxRows(int max) throws SQLException;
public int getMaxRows() throws SQLException;
public void setQueryTimeout(int seconds) throws SQLException;
public int getQueryTimeout() throws SQLException;
public void setFetchSize(int rows) throws SQLException;
public int getFetchSize() throws SQLException;
public void setFetchDirection(int direction) throws SQLException;
public int getFetchDirection() throws SQLException;
// Cursor and result set types
public void setCursorName(String name) throws SQLException;
public int getResultSetType() throws SQLException;
public int getResultSetConcurrency() throws SQLException;
public int getResultSetHoldability() throws SQLException;
// Warnings and metadata
public SQLWarning getWarnings() throws SQLException;
public void clearWarnings() throws SQLException;
public Connection getConnection() throws SQLException;
// Generated keys
public ResultSet getGeneratedKeys() throws SQLException;
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException;
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException;
public int executeUpdate(String sql, String[] columnNames) throws SQLException;
// Cleanup
public void close() throws SQLException;
public boolean isClosed() throws SQLException;
}Usage Examples:
// Basic statement execution
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
// Execute query
ResultSet rs = stmt.executeQuery("SELECT id, name, email FROM users");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
System.out.println(id + ": " + name + " (" + email + ")");
}
// Execute update
int affectedRows = stmt.executeUpdate("UPDATE users SET active = 1 WHERE last_login > '2023-01-01'");
System.out.println("Updated " + affectedRows + " users");
// Execute with generated keys
int newRows = stmt.executeUpdate(
"INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')",
Statement.RETURN_GENERATED_KEYS
);
ResultSet generatedKeys = stmt.getGeneratedKeys();
if (generatedKeys.next()) {
long newId = generatedKeys.getLong(1);
System.out.println("Created user with ID: " + newId);
}
// Batch operations
stmt.addBatch("INSERT INTO logs (message) VALUES ('Event 1')");
stmt.addBatch("INSERT INTO logs (message) VALUES ('Event 2')");
stmt.addBatch("INSERT INTO logs (message) VALUES ('Event 3')");
int[] batchResults = stmt.executeBatch();Prepared statement implementations for secure and efficient parameterized queries.
/**
* Base class for prepared statements
*/
public abstract class BasePreparedStatement implements PreparedStatement {
// Parameter setting methods
public void setNull(int parameterIndex, int sqlType) throws SQLException;
public void setBoolean(int parameterIndex, boolean x) throws SQLException;
public void setByte(int parameterIndex, byte x) throws SQLException;
public void setShort(int parameterIndex, short x) throws SQLException;
public void setInt(int parameterIndex, int x) throws SQLException;
public void setLong(int parameterIndex, long x) throws SQLException;
public void setFloat(int parameterIndex, float x) throws SQLException;
public void setDouble(int parameterIndex, double x) throws SQLException;
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException;
public void setString(int parameterIndex, String x) throws SQLException;
public void setBytes(int parameterIndex, byte[] x) throws SQLException;
public void setDate(int parameterIndex, Date x) throws SQLException;
public void setTime(int parameterIndex, Time x) throws SQLException;
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException;
public void setObject(int parameterIndex, Object x) throws SQLException;
// LOB methods
public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException;
public void setCharacterStream(int parameterIndex, Reader x) throws SQLException;
public void setBlob(int parameterIndex, Blob x) throws SQLException;
public void setClob(int parameterIndex, Clob x) throws SQLException;
// Execution methods
public ResultSet executeQuery() throws SQLException;
public int executeUpdate() throws SQLException;
public boolean execute() throws SQLException;
// Batch operations
public void addBatch() throws SQLException;
public int[] executeBatch() throws SQLException;
// Metadata
public ParameterMetaData getParameterMetaData() throws SQLException;
// Parameter management
public void clearParameters() throws SQLException;
}
/**
* Client-side prepared statement implementation
*/
public class ClientPreparedStatement extends BasePreparedStatement {
// Client-side parameter processing and SQL generation
// Parameters are processed on the client and SQL is generated locally
}
/**
* Server-side prepared statement implementation
*/
public class ServerPreparedStatement extends BasePreparedStatement {
// Server-side statement preparation and execution
// Statements are prepared on the database server for better performance
}Usage Examples:
// Basic prepared statement
String sql = "SELECT * FROM users WHERE age > ? AND city = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 21);
pstmt.setString(2, "New York");
ResultSet rs = pstmt.executeQuery();
// Insert with prepared statement
String insertSql = "INSERT INTO users (name, email, age, created_at) VALUES (?, ?, ?, ?)";
PreparedStatement insertStmt = conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);
insertStmt.setString(1, "Alice Smith");
insertStmt.setString(2, "alice@example.com");
insertStmt.setInt(3, 28);
insertStmt.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
int rows = insertStmt.executeUpdate();
// Get generated keys
ResultSet keys = insertStmt.getGeneratedKeys();
if (keys.next()) {
long userId = keys.getLong(1);
System.out.println("Created user ID: " + userId);
}
// Batch prepared statements
PreparedStatement batchStmt = conn.prepareStatement("INSERT INTO products (name, price) VALUES (?, ?)");
batchStmt.setString(1, "Product A");
batchStmt.setBigDecimal(2, new BigDecimal("19.99"));
batchStmt.addBatch();
batchStmt.setString(1, "Product B");
batchStmt.setBigDecimal(2, new BigDecimal("29.99"));
batchStmt.addBatch();
int[] batchResults = batchStmt.executeBatch();
// Working with LOBs
PreparedStatement lobStmt = conn.prepareStatement("INSERT INTO documents (name, content) VALUES (?, ?)");
lobStmt.setString(1, "document.pdf");
// Set binary content
FileInputStream fileInput = new FileInputStream("document.pdf");
lobStmt.setBinaryStream(2, fileInput);
lobStmt.executeUpdate();
// Set text content
String textContent = "This is a large text document...";
lobStmt.setString(1, "text_doc.txt");
lobStmt.setCharacterStream(2, new StringReader(textContent));
lobStmt.executeUpdate();Support for stored procedures and database functions.
/**
* Base callable statement for stored procedures and functions
*/
public class BaseCallableStatement extends BasePreparedStatement implements CallableStatement {
// Output parameter registration
public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException;
public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException;
public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException;
public void registerOutParameter(String parameterName, int sqlType) throws SQLException;
// Named parameter support
public void setString(String parameterName, String x) throws SQLException;
public void setInt(String parameterName, int x) throws SQLException;
public void setNull(String parameterName, int sqlType) throws SQLException;
// Output parameter retrieval
public String getString(int parameterIndex) throws SQLException;
public int getInt(int parameterIndex) throws SQLException;
public boolean getBoolean(int parameterIndex) throws SQLException;
public byte getByte(int parameterIndex) throws SQLException;
public short getShort(int parameterIndex) throws SQLException;
public long getLong(int parameterIndex) throws SQLException;
public float getFloat(int parameterIndex) throws SQLException;
public double getDouble(int parameterIndex) throws SQLException;
public BigDecimal getBigDecimal(int parameterIndex) throws SQLException;
public Date getDate(int parameterIndex) throws SQLException;
public Time getTime(int parameterIndex) throws SQLException;
public Timestamp getTimestamp(int parameterIndex) throws SQLException;
public Object getObject(int parameterIndex) throws SQLException;
// Named output parameter retrieval
public String getString(String parameterName) throws SQLException;
public int getInt(String parameterName) throws SQLException;
public boolean getBoolean(String parameterName) throws SQLException;
// Null checking
public boolean wasNull() throws SQLException;
}
/**
* Callable statement for stored procedures
*/
public class ProcedureStatement extends BaseCallableStatement {
// Specialized for stored procedure calls
}
/**
* Callable statement for database functions
*/
public class FunctionStatement extends BaseCallableStatement {
// Specialized for function calls
}Usage Examples:
// Call stored procedure with IN and OUT parameters
String procedureCall = "{call getUserStats(?, ?)}";
CallableStatement cstmt = conn.prepareCall(procedureCall);
// Set input parameter
cstmt.setInt(1, 100); // user_id
// Register output parameter
cstmt.registerOutParameter(2, Types.INTEGER); // user_count
// Execute procedure
cstmt.execute();
// Get output parameter value
int userCount = cstmt.getInt(2);
System.out.println("User count: " + userCount);
// Call function
String functionCall = "{? = call calculateTax(?, ?)}";
CallableStatement funcStmt = conn.prepareCall(functionCall);
// Register return value
funcStmt.registerOutParameter(1, Types.DECIMAL);
// Set input parameters
funcStmt.setBigDecimal(2, new BigDecimal("1000.00")); // amount
funcStmt.setBigDecimal(3, new BigDecimal("0.08")); // tax_rate
// Execute function
funcStmt.execute();
// Get return value
BigDecimal tax = funcStmt.getBigDecimal(1);
System.out.println("Tax: " + tax);
// Named parameters (if supported by procedure)
String namedCall = "{call createUser(?, ?, ?)}";
CallableStatement namedStmt = conn.prepareCall(namedCall);
namedStmt.setString("user_name", "John Doe");
namedStmt.setString("user_email", "john@example.com");
namedStmt.registerOutParameter("user_id", Types.BIGINT);
namedStmt.execute();
long newUserId = namedStmt.getLong("user_id");Advanced result set handling and navigation.
// Scrollable result sets
Statement scrollStmt = conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY
);
ResultSet scrollRs = scrollStmt.executeQuery("SELECT * FROM large_table");
// Navigate result set
scrollRs.first(); // Go to first row
scrollRs.last(); // Go to last row
scrollRs.absolute(100); // Go to row 100
scrollRs.relative(-10); // Move back 10 rows
scrollRs.previous(); // Previous row
// Updatable result sets
Statement updateStmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE
);
ResultSet updateRs = updateStmt.executeQuery("SELECT id, name, salary FROM employees");
while (updateRs.next()) {
double salary = updateRs.getDouble("salary");
if (salary < 50000) {
// Update salary in place
updateRs.updateDouble("salary", salary * 1.1);
updateRs.updateRow();
}
}
// Insert new row
updateRs.moveToInsertRow();
updateRs.updateString("name", "New Employee");
updateRs.updateDouble("salary", 60000);
updateRs.insertRow();
updateRs.moveToCurrentRow();
// Large result set streaming
Statement streamStmt = conn.createStatement();
streamStmt.setFetchSize(1000); // Process in chunks of 1000 rows
ResultSet streamRs = streamStmt.executeQuery("SELECT * FROM huge_table");
// Process results in chunks to manage memory
while (streamRs.next()) {
// Process row without loading entire result set into memory
processRow(streamRs);
}Advanced statement configuration options.
// Statement timeouts and limits
Statement configStmt = conn.createStatement();
configStmt.setQueryTimeout(30); // 30 second timeout
configStmt.setMaxRows(10000); // Limit to 10,000 rows
configStmt.setFetchSize(500); // Fetch 500 rows at a time
configStmt.setFetchDirection(ResultSet.FETCH_FORWARD);
// Prepared statement configuration
PreparedStatement configPstmt = conn.prepareStatement(
"SELECT * FROM users WHERE created_at > ?",
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT
);
// Enable statement pooling (server-side prepared statements)
String poolingUrl = "jdbc:mariadb://localhost:3306/mydb?" +
"useServerPrepStmts=true&" +
"cachePrepStmts=true&" +
"prepStmtCacheSize=250&" +
"prepStmtCacheSqlLimit=2048";
Connection poolConn = DriverManager.getConnection(poolingUrl, user, password);
PreparedStatement pooledStmt = poolConn.prepareStatement("SELECT * FROM users WHERE id = ?");
// This statement will be cached on the server for reuse// Use bulk statements for better performance
String bulkUrl = "jdbc:mariadb://localhost:3306/mydb?useBulkStmts=true";
Connection bulkConn = DriverManager.getConnection(bulkUrl, user, password);
// Bulk insert
PreparedStatement bulkInsert = bulkConn.prepareStatement(
"INSERT INTO log_entries (timestamp, level, message) VALUES (?, ?, ?)"
);
// Add multiple rows to batch
for (LogEntry entry : logEntries) {
bulkInsert.setTimestamp(1, entry.getTimestamp());
bulkInsert.setString(2, entry.getLevel());
bulkInsert.setString(3, entry.getMessage());
bulkInsert.addBatch();
}
// Execute all at once with bulk protocol
int[] results = bulkInsert.executeBatch();// Client-side statement caching
String cacheUrl = "jdbc:mariadb://localhost:3306/mydb?" +
"cachePrepStmts=true&" + // Enable caching
"prepStmtCacheSize=250&" + // Cache up to 250 statements
"prepStmtCacheSqlLimit=2048"; // Cache statements up to 2KB
// Server-side prepared statements
String serverPrepUrl = "jdbc:mariadb://localhost:3306/mydb?" +
"useServerPrepStmts=true&" + // Use server-side preparation
"cachePrepStmts=true"; // Cache prepared statements
// Statements will be automatically cached and reused
Connection cacheConn = DriverManager.getConnection(cacheUrl, user, password);
PreparedStatement cachedStmt = cacheConn.prepareStatement("SELECT * FROM users WHERE id = ?");
// Subsequent prepareStatement calls with same SQL will reuse cached statementInstall with Tessl CLI
npx tessl i tessl/maven-org-mariadb-jdbc--mariadb-java-client