2
votes

I have Connect() method which has a string paramater, this parameter is an input from the user. I have 2 databases created: test and test2, but I can only connect to test db from user input. Should I made changes to the server that host the 2 dbs so to be able to connect to any database that user writes???

  public void Connect(String DataBase) {
            try{
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + DataBase);
                st = con.createStatement();
                System.out.println("Connected to " + DataBase + " !!!");
                con.close();
            }catch(SQLException se){
                System.out.println("Cannot connect to database " + DataBase);
            }
            catch(Exception ex){
                System.out.println("Error: " + ex);
            }  
        }

MAIN METHOD

   // DB1Connect connect = new DBConnect("test");
    //connect.getData();

    Scanner scanner = new Scanner(System.in);
    System.out.println("Choose from these choices");
    System.out.println("-------------------------\n");
    System.out.println("1 - Connect to a specific DB schema");
    System.out.println("2 - List DB schema structure: tables, fields, types");
    System.out.println("3 - List table structure: fields, types");
    System.out.println("4 - Quit");
    int choice = scanner.nextInt();
     switch(choice) {
         case 1:
             System.out.println("Enter the Db's name:");
             String dbName = scanner.next();
             DBConnect connect = new DBConnect();
             connect.Connect(dbName);
             break;
         case 2:

             break;
         default:
             System.out.println("Incorrect option");
     }
}

STACK TRACE:

Enter the Db's name:
test2
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Access denied for user ''@'localhost' to database 'test2'
Cannot connect to database test2
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.Util.getInstance(Util.java:381)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:910)
    at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3923)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1273)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2031)
    at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:718)
    at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:46)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:270)
    at medapp.DBConnect.Connect(DBConnect.java:19)
    at medapp.MedApp.main(MedApp.java:29)
2
Why do you say you can only connect to the test database? What happens if the user enters test2? - RealSkeptic
An exception is thrown and enters here catch(SQLException se){ System.out.println("Cannot connect to database " + DataBase); } - Andrei Maieras
when input is test it prints Connected to test!!! - Andrei Maieras
How about adding se.printStackTrace() to that catch and copying the full stack trace to your question? - RealSkeptic
You have an edit link under the question. Write something like "This is the stack trace", then paste the stack trace, then add <pre> at its beginning and </pre> at its end to format it. - RealSkeptic

2 Answers

1
votes

Try connecting to the database after establishing a connection with the server.

  public void Connect(String DataBase) {
            try{
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/");
                st = con.createStatement();
                st.execute("USE " + "[" + DataBase + "]");
                System.out.println("Connected to " + DataBase + " !!!");
                con.close();
            }catch(SQLException se){
                System.out.println("Cannot connect to database " + DataBase);
            }
            catch(Exception ex){
                System.out.println("Error: " + ex);
            }  
        }

Does the database require authenication? If so try this:

Properties connProperties;
connProperties = new Properties();
connProperties.setProperty("user", getUsername());
connProperties.setProperty("password",getPassword());

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + DataBase, connProperties);

Also, it a good idea to check if database exist

stat.executeQuery("SELECT * FROM sys.sysdatabases");
0
votes

The stack trace tells you that you have a SQLSyntax error. Using this you can trace back the error. In this case, the last X2 lines in the StackTrace:

"at medapp.DBConnect.Connect(DBConnect.java:19) at medapp.MedApp.main(MedApp.java:29)"

Are telling you that there is an error with the "medapp" class with the methods of "main" and "Connect".

Might I suggest that you contain the connection to a database to a different class from each-other? The alternative would be to close all connections with the .close() method/.

Differing classes


Scanner decision = new Scanner(System.in);
String choice = decision.next();

if(choice.trim().equals("test");
{
    //enter class to connect to "test" table
}
if(choice.trim().equals("test2")
{
    //enter class to connect to "test2" table
}

If you're planning on going back to main or switching tables during runtime, I'd recommend adding a finally block to close connections before making the transition.


The alternative to the above would be to have a method in your main class dedicated to each connection, with a method to close the connection for a re-connect.


EDIT

Based on the response, I would highly suggest checking the status of both tables. Install the MySQL Workbench (found here) and connect to your databases with it. This should aid you in debugging your connection issues.

Might I also suggest, go-over your code and ensure there are no spelling mistakes within your SQL Statement.