I write methods for createConnection and createDatabase in class methods. Connection is getting created successfully but database is not creating because of wrong input for SQL query.
class methods{
public static Connection CreateConnection() throws SQLException, ClassNotFoundException
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/","root","baby");
System.out.println("connected to Mysql database");
return con;
}
public static void createDatabase(Connection con) throws SQLException {
System.out.println("Enter database name :");
Scanner sc = new Scanner(System.in);
String q1 = "CREATE DATABASE ?";
PreparedStatement smt = con.prepareStatement(q1);
String databasename = sc.next();
smt.setString(1, databasename);
smt.executeUpdate();
System.out.println("Database created.");
}
}
Main class
public class Main {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection con = methods.CreateConnection();
methods.createDatabase(con);
}
Output
Enter database name :
data
Exception in thread "main" java.sql.SQLSyntaxErrorException: 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 mysql.connector.java@8.0.15/com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at mysql.connector.java@8.0.15/com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at mysql.connector.java@8.0.15/com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at mysql.connector.java@8.0.15/com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:970)
at mysql.connector.java@8.0.15/com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1109)
at mysql.connector.java@8.0.15/com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1057)
at mysql.connector.java@8.0.15/com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1377)
at mysql.connector.java@8.0.15/com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1042)
at jdbc.methods.createDatabase(methods.java:28)
at jdbc.Main.main(Main.java:12)
Print PreparedStatement
to see the problem origin:
System.out.println(smt);
smt.executeUpdate();
Assuming that user entered StudentDB
as database name, printed statement would be:
CREATE DATABASE 'StdudentDB'
That is invalid and should be:
CREATE DATABASE StdudentDB
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.