CREATE DATABASE query using java jdbc and prepared statement returns 语法错误

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

我试图让 Java 使用 JDBC 创建数据库,但我收到语法错误,尽管查询是正确的。例如,如果我将数据库的名称显式写入代码,它就可以正常工作。这是我的代码:

package mysql_manipulator;

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

public class Create {
    private static final String 
            driver = "com.mysql.jdbc.Driver",
            url = "jdbc:mysql://localhost",
            username = "dylan",
            password = "******";
    private String databaseName;

    public Create (){
        this.databaseName = null;
    }

    public String getDatabaseName() {
        return databaseName;
    }

    public void setDatabaseName(String databaseName) {
        this.databaseName = databaseName;
    }

    public void createDatabase(String databaseName){
        try {
            this.setDatabaseName(databaseName);        
            Class.forName(driver);
            Connection con = DriverManager.getConnection(url,username, 
                password);
            String query = "CREATE DATABASE ?";
            PreparedStatement preparedStmt = con.prepareStatement(query);
            preparedStmt.setString (1,this.getDatabaseName());
            preparedStmt.execute();
            preparedStmt.close();
            con.close();        
        }
        catch (Exception anException){
            System.out.println("Error: " + anException);
        }
    }
}  

我的主Class

package mysql_manipulator;

public class Mysql_manipulator {
    public static void main(String[] args) {
        Create myObj = new Create();
        myObj.createDatabase("whatevs");        
    }    
}

错误

Error: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You  have an error in
your SQL syntax; check the manual that corresponds to your  MariaDB server version 
for the right syntax to use near ''whatevs'' at line 1

非常感谢任何知道为什么这不起作用的人 - 我在整个网络上搜索都无济于事。

您不能将数据库名称作为绑定变量——您必须将其嵌入到查询文字中。将您的查询改为:

String query = "CREATE DATABASE " + getDatabaseName();

对于 运行 这个 SQL.

,您也可以使用普通的 Statement(而不是 PreparedStatement
Conn = DriverManager.getConnection 
("jdbc:mysql://localhost/?user=root&password=rootpassword"); 
Statement s=Conn.createStatement(); 

int Result=s.executeUpdate("CREATE DATABASE databasename");

http://forums.mysql.com/read.php?39,99321,102211#msg-102211

Create MySQL database from Java