2

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.

4
  • What is 'info' keyword in your sql query? Haven't seen it before. Commented Oct 1, 2015 at 9:00
  • And by the way, when you make several changes in a single query always put the whole query in a transaction to prevent incomplete changes. Commented Oct 1, 2015 at 9:02
  • @Timofey: not sure about MySQL but not all databases (e.g. Oracle) allow DDL in transactions. Commented Oct 1, 2015 at 9:19
  • @Timofey It's not a keyword, it's the name of the table in my database Commented Oct 2, 2015 at 9:12

2 Answers 2

2

Do a batch:

        String[] sqlStatements = new String[] {
                "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 = null;
        try {
            connection = createConnection(user, password);
            Statement statement = connection.createStatement();
            for (String sqlStatement : sqlStatements) {
                statement.addBatch(sqlStatement);
            }
            int[] result = statement.executeBatch();
            for (int i = 0; i < result.length; i++) {
                System.out.println(sqlStatements[i] + " - " + result[i]);
            }
            System.out.println(result);
            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();
                }
        }
Sign up to request clarification or add additional context in comments.

Comments

1

Your problem may be due to the fact that you didn't set the multiple query property on your database connection, so it is executing only the first statement. Try modifying the database url like this:

jdbc:mysql:<your_url>?allowMultiQueries=true

1 Comment

Thank you so much! That was the problem. Now it works as it should

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.