我正在尝试创建一个程序,从用户那里获取输入并使用输入作为数据库名创建一个mysql数据库,我成功创建了数据库,但只有当我自己在代码中输入数据库名称时,我才会想到到目前为止
package mqsljava;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Scanner;
public class Mqsljava {
//CONNECTION
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String username = "root";
String password = "";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void main(String[] args) {
//THE VARIABLE TO STORE USER INPUT
String Data;
//SCANNER TO GET USER INPUT
Scanner Dbname = new Scanner(System.in);
System.out.println("Enter your db name");
//VARIABLE SAVES USER INPUT
Data = Dbname.nextLine();
//WHERE THE PROBLEM IS, USING USER INPUT DATA TO CREATE DATABASE
String EMPLOYEE_DB = " CREATE DATABASE '"+Data+"' ";
Connection conn = null;
Statement stmt = null;
try {
conn = getConnection();
stmt = conn.createStatement();
stmt.executeUpdate(EMPLOYEE_DB);
System.out.println("Database created.");
} catch (ClassNotFoundException e) {
System.out.println("error: failed to load MySQL driver.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("error: failed to create a connection object.");
e.printStackTrace();
} catch (Exception e) {
System.out.println("other error:");
e.printStackTrace();
} finally {
try {
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
但我一直收到错误
com.mysql.jdbc.exceptions.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 ''Data'' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3277)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1402)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1317)
at mqsljava.Mqsljava.main(Mqsljava.java:52)
我认为我没有使用正确的陈述,我尝试了很多东西,但仍然无法正常工作
答案 0 :(得分:2)
要创建数据库,您不需要使用Supplier
,您必须使用不带'DB_NAME'
的名称,如下所示:
''
与@baao在评论中提及一样,您的方式不安全且对SQL注入开放,您必须在查询中使用它之前检查名称。