everyone! I'm trying to create a database using java. Here's the code
public void createDatabase(String user, String password) {
String query = "CREATE DATABASE IF NOT EXISTS Contacts;use Contacts;CREATE TABLE IF NOT EXISTS info(first_name TEXT,surname TEXT,login TEXT,email TEXT,phone_number INT NOT NULL primary key)";
Connection connection = createConnection(user, password);
try {
Statement statement = connection.createStatement();
int result = statement.executeUpdate(query);
System.out.println("Database is ready for use");
} catch (SQLException e1) {
e1.printStackTrace();
}
finally {
if (connection != null)
try {
connection.close();
System.out.println("Connection closed");
} catch (SQLException e) {
e.printStackTrace();
}
After running this I get
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'use Contacts;CREATE TABLE IF NOT EXISTS info(first_name TEXT,surname TEXT,login ' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:400)
at com.mysql.jdbc.Util.getInstance(Util.java:383)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:980)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2541)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1604)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1535)
at task.DatabaseManager.createDatabase(DatabaseManager.java:28)
at task.Test.main(Test.java:14)
Connection closed
The database is created, but the tables are not. So the problem is somewhere there. And one more thing. When I paste this query into MySQL Workbench and execute it - it works perfectly and creates everything I need.