0

I just started learning about MySQL and I am now trying to learn prepared statements. When I uses them, I get this error java.sql.SQLSyntaxErrorException. Can someone tell me where am I getting the syntax wrong? Thanks. Here is my code:

public class DBConnector {
    
    private Statement statement;
    private ResultSet result;
    private PreparedStatement preparedStatement;

    public void createDB() { 
            try {
                sql = "CREATE DATABASE IF NOT EXISTS ?";
                tableName = "test_name";
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1, tableName);
                int myResult = preparedStatement.executeUpdate();
    
                if(myResult == 1){
                    System.out.println("Database successfully created.");
                }else{
                    System.out.println("Database with that name already exists. Please try again with different name.");
                    createDB();
                }
            }catch (SQLException e) {
                System.out.println("Database creation failed.");

            e.printStackTrace();
        }
    }
}
1
  • I am not sure what is your use case, but creating database in application code is not advisable unless you are creating a database management application like phpMyAdmin. Commented Jul 12, 2021 at 12:42

1 Answer 1

1

We can't bind Database names in Query parameters.

Statement stmt=con.createStatement(); 

int rs=stmt.executeUpdate("CREATE DATABASE dbname");

Try in this way, Database will create.

Sign up to request clarification or add additional context in comments.

3 Comments

Didn't know that! Thank you so much!
it works but l cant set custom names that way... I wanted to give the user freedom to set his own db name. Thx anyways.
String sql = "create database " +obj.getDbName(); you can pass in this way as well

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.