简体   繁体   中英

Connecting to external mysql database using Java

I am trying to connect to a external database , but it seems that i may be making a mistake on the way i am putting the DriverManager connection, this is the first time i am connecting using this driver, Can you please point me in the right direction? thank you (might be something wrong on the getConnection call)

Class.forName( "com.mysql.jdbc.Driver" ) ;

       // Get a connection to the database
       Connection conn = DriverManager.getConnection( "jdbc:mysql://cs.cis.can.edu;databaseName=mar200;user=utest;password=utest" ) ;

Error

SQL Exception:
State  : 08S01
Message: Communications link failure

Last packet sent to the server was 0 ms ago.
Error  : 0

instead of passing one string argument, try passing each separatly like

    getConnection(String url, String user, String password)

here is the guide to the DriverManager class http://docs.oracle.com/javase/7/docs/api/java/sql/DriverManager.html

Instead of passing argument in one instance you can use separate of username, password and driver.

Connection conn = null;

           try
           {
               String userName = "testuser";
               String password = "testpass";
               String url = "jdbc:mysql://localhost/test";
               Class.forName ("com.mysql.jdbc.Driver").newInstance ();
               conn = DriverManager.getConnection (url, userName, password);
               System.out.println ("Database connection established");
           }
           catch (Exception e)
           {
               System.err.println ("Cannot connect to database server");
           }
           finally
           {
               if (conn != null)
               {
                   try
                   {
                       conn.close ();
                       System.out.println ("Database connection terminated");
                   }
                   catch (Exception e) { /* ignore close errors */ }
               }
           }

http://www.kitebird.com/articles/jdbc.html

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM