如何以编程方式为mysql jdbc驱动程序设置rewriteBatchedStatements?

Che*_*rry 5 java mysql jdbc

是一种加快批量插入性能的方法.可以rewriteBatchedStatements以编程方式设置,而不是通过网址设置?

Mar*_*eel 3

如果您不想通过 URL 执行此操作,则可以使用该Properties对象DriverManager

Properties props = new Properties();
props.setProperty("user", ...);
props.setProperty("password", ...);
props.setProperty("rewriteBatchedStatements", "true");
Connection connection = DriverManager.getConnection(url, props);
Run Code Online (Sandbox Code Playgroud)

如果您使用MysqlDataSourceorMysqlConnectionPoolDataSource那么您需要设置属性rewriteBatchedStatements(或调用 settersetRewriteBatchedStatements(boolean)

要在获得连接后在运行时更改此设置,您应该能够使用:

((com.mysql.jdbc.ConnectionProperties) connection).setRewriteBatchedStatements(true);
Run Code Online (Sandbox Code Playgroud)

注意:我只查看了最后一个选项的 MySQL Connector/J 源代码,尚未对其进行测试。

更新

对于c3p0,您可以使用以下命令:

ComboPooledDataSource cpds = ...
Connection connection = cpds.getConnection();
connection.unwrap(com.mysql.jdbc.ConnectionProperties.class).setRewriteBatchedStatements(true);
Run Code Online (Sandbox Code Playgroud)

c3p0 应该是com.mchange:c3p0:0.9.5.2,小心com.mchange- 对于其他 groupId,此代码不起作用。