如何在一个mysql db容器上创建多个数据库? 还是我必须为每个数据库创建数据库容器? 当我尝试从sql文件脚本创建它时:
@ClassRule public static MySQLContainer dbService = (MySQLContainer) new MySQLContainer()
.withPassword("test")
.withUsername("mysqlroot")
.withDatabaseName("test")
.withInitScript("init_mysql.sql")
.withExposedPorts(DB_PORT)
.withNetwork(network)
.withNetworkAliases("dbService")
;
我遇到错误:
Caused by: org.testcontainers.ext.ScriptUtils$ScriptStatementFailedException: Script execution failed (init_mysql.sql:2): CREATE DATABASE IF NOT EXISTS `b2c`
at org.testcontainers.jdbc.JdbcDatabaseDelegate.execute(JdbcDatabaseDelegate.java:49)
at org.testcontainers.delegate.AbstractDatabaseDelegate.execute(AbstractDatabaseDelegate.java:34)
at org.testcontainers.ext.ScriptUtils.executeDatabaseScript(ScriptUtils.java:331)
... 19 more
Caused by: java.sql.SQLSyntaxErrorException: Access denied for user 'mysqlroot'@'%' to database 'b2c'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:782)
at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:666)
at org.testcontainers.jdbc.JdbcDatabaseDelegate.execute(JdbcDatabaseDelegate.java:42)
... 21 more
init_mysql.sql
CREATE TABLE bar (
foo VARCHAR(255)
);
CREATE DATABASE IF NOT EXISTS `b2c`;
我尝试了许多配置。对我来说,除了在容器创建时配置的专用数据库外,我无法执行sql。 请帮忙。我有6个数据库,为每个数据库创建专用容器是浪费资源。
答案 0 :(得分:1)
首先,您需要使用root
用户名来启动MySQLContainer(以具有执行初始化脚本的特权):
new MySQLContainer<>(new DockerImageName(MYSQL_DOCKER_IMAGE))
.withUsername("root")
.withPassword("")
.withEnv("MYSQL_ROOT_HOST", "%")
.withInitScript("init_test_container_databases.sql")
.withNetwork(NETWORK)
.withNetworkAliases(MYSQL_NETWORK)
.withStartupTimeout(Duration.ofSeconds(CONTAINER_STARTUP_TIMEOUT_SECONDS));
init_test_container_databases.sql
脚本(在我的示例中,我用同一用户创建了两个数据库,供我的应用程序使用):
CREATE DATABASE IF NOT EXISTS your_database_1;
CREATE DATABASE IF NOT EXISTS your_database_2;
CREATE USER 'your_username'@'%' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON *.* TO 'your_username'@'%';