Following code is used to connect to a MySQL database.

Java Code:
Connection conn = null;

           try
           {
               String userName = "user1";
               String password = "pass1";
               String url = "jdbc:mysql://localhost/testdb";
               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) {}
               }
           }