I have some MySQL scripts that are needed for recreating a database. They work fine when I execute them on the command line using the mysql
command.
Now I wrote a Java class that should execute these scripts using a JDBC connection to the MySQL database.
One line in a "create table"-statement in the script is:
registration_date DATETIME DEFAULT CURRENT_TIMESTAMP
This line however won't be executed using the JDBC-MySQL connection. I get the error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Invalid default value for 'registration_date'
The relevant method is shown below. sqlScriptPath
points to the folder containing the sql scripts. The connectionString has this content: "jdbc:mysql://localhost:3306/testDb?useUnicode=yes&characterEncoding=UTF-8&allowMultiQueries=true"
public static void recreate(String connectionString, String dbUser, String dbPass, String sqlScriptPath) throws Exception {
// Find and filter sql scripts
File file = new File(sqlScriptPath);
File[] scripts = file.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.getName().endsWith(".sql");
}
});
List<File> scriptsList = Arrays.asList(scripts);
Collections.sort(scriptsList);
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(connectionString, dbUser, dbPass);
// Load each script and apply it
for (File f : scriptsList) {
System.out.println("Importing script: " + f);
List<String> lines = Files.readAllLines(Paths.get(f.getAbsolutePath()), Charset.forName("UTF-8"));
StringBuilder sb = new StringBuilder();
for (String line : lines) sb.append(line).append("\n");
String sqlStatement = sb.toString();
System.out.print(sqlStatement);
Statement st = conn.createStatement();
st.execute(sqlStatement);
st.close();
}
}
And the relevant part of the script:
CREATE TABLE user
(
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
username VARCHAR(255),
password VARCHAR(255),
age_group INT,
registration_date DATETIME DEFAULT CURRENT_TIMESTAMP
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8;
What is the problem here?