小编典典

使用Java jdbc和Prepared语句创建数据库查询返回语法错误

java

我正在尝试让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);
        }
    }
}

我的主班

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

非常感谢任何知道为什么此方法不起作用的人-我在网上搜索了无济于事。


阅读 222

收藏
2020-11-19

共1个答案

小编典典

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

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

您也可以使用普通Statement(而不是PreparedStatement)来运行此SQL。

2020-11-19