1

I'm trying to create a database with java jdbc with a method so i'm passing the name type string of database as argument to database but i'm facing an issue which is 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 ''Algebra'' at line 1

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DbTest {
private Connection connection;
public void createDb(String name) throws SQLException {
    connection = DriverManager.getConnection
            ("jdbc:mysql://localhost/?user=root&password=root");

    String createDbSql = "CREATE DATABASE IF NOT EXISTS ?";
    PreparedStatement createDbStat = connection.prepareStatement(createDbSql);
    createDbStat.setString(1,name);
    createDbStat.executeUpdate();
}

DbTest() {
    try {
        createDb("Algebra");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    new DbTest();
}
}
blabla
  • 69
  • 8

2 Answers2

3

When you use createDbStat.setString(1, name); it will create a query like this :

CREATE DATABASE IF NOT EXISTS 'databasename'
//----------------------------^____________^

And this is a wrong syntax, the correct should be :

CREATE DATABASE IF NOT EXISTS databasename

to solve your problem you can just use :

String createDbSql = String.format("CREATE DATABASE IF NOT EXISTS `%s`", name);
//                                                                ^^^^
PreparedStatement createDbStat = connection.prepareStatement(createDbSql);
//createDbStat.setString(1,name); no need for this
createDbStat.executeUpdate();

For security reason

Just for security reason, and to avoid SQL Injection make sure that your database name match this:

if(name.matches("^[a-zA-Z_][a-zA-Z0-9_]*$")){
   //Correct name
}

for more details read this Check for valid SQL column name

Community
  • 1
  • 1
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

You can't bind your parameter (1) to the database name- you'll have to use string concatenation in this case.

Your question is also similar to

How to use a tablename variable for a java prepared statement insert

and

CREATE DATABASE query using java jdbc and prepared statement returns syntax error

Daniele
  • 2,672
  • 1
  • 14
  • 20