连接到用户输入数据库

时间:2015-03-24 20:16:47

标签: java mysql

我有Connect()方法,它有一个字符串参数,这个参数是来自用户的输入。我创建了2个数据库:test和test2,但我只能从用户输入连接到测试数据库。我是否应该对托管2 dbs的服务器进行更改,以便能够连接到用户写入的任何数据库?

  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);
            }  
        }

主要方法

   // 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 个答案:

答案 0 :(得分:1)

在与服务器建立连接后尝试连接到数据库。

  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);
            }  
        }

数据库是否需要验证?如果是这样,试试这个:

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

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

另外,检查数据库是否存在是个好主意

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

答案 1 :(得分:0)

堆栈跟踪告诉您有SQLSyntax错误。使用此功能可以追溯错误。在这种情况下,StackTrace中的最后一行X2行:

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

告诉您“medapp”类使用“main”和“Connect”方法时出错。

我可能建议您将数据库的连接包含在彼此不同的类中吗?另一种方法是使用.close()方法/.

关闭所有连接

不同的课程


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
}

如果您计划在运行时返回主表或切换表,我建议在进行转换之前添加finally块以关闭连接。


上面的替代方法是在主类中有一个专用于每个连接的方法,以及一种关闭连接以重新连接的方法。


修改

根据回复,我强烈建议检查两个表的状态。安装MySQL Workbench(找到here)并使用它连接到您的数据库。这可以帮助您调试连接问题。

我可能会建议,重新检查代码并确保SQL语句中没有拼写错误。