I try to initialise my database in Java by running testdb.sql file
private static Connection con;
private static void initConenction() throws SQLException{
//Getting the connection
String url = "jdbc:mysql://localhost:3306/testDB?allowMultiQueries=true";
final String userName = "root";
final String password = "mypassword";
try {
con = DriverManager.getConnection(url, userName, password);
System.out.println("Connection established!");
} catch (SQLException e) {
e.printStackTrace();
throw e;
}
}`
private static void initDatabase() throws SQLException, IOException {
try{
Statement stmt = con.createStatement();
String sqlStr = Files.readString(Paths.get("src/testdb.sql"));
stmt.execute(sqlStr);
System.out.println("Database initialization completed!");
} catch (IOException e) {
System.out.format("I/O error: %s%n", e);
throw e;
}catch (SQLException e){
e.printStackTrace();
throw e;
}
}
And here is the testdb.sql
CREATE DATABASE IF NOT EXISTS testDB;
USE testDB;
CREATE TABLE USERS(
userType VARCHAR(50) not null,
userName VARCHAR(100) not null,
password VARCHAR(100) not null,
primary key(userName)
);
I ran the SQL exactly the same in MySQL bench and it works, but why when I try to do it in java it fails and warns error in SQL syntax? Here is the error message:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE TABLE USERS( userType VARCHAR(50) not null, userName VARCHAR(100)' at line 3
I expect to create table in database by codes in Java
USE testDBstatement and you should remove it. Also, remove the semicolon at the end of the SQL statement.jdbc:mysql://server_ip_here:3306/testdb(or useConnection.setCatalog()method in your code to select the database as suggested by Mark in his answer below)userName VARCHAR(100).