Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (6.1k points)

I attempted to connect a MySQL database I have a free hosting account, although I am not able to connect to MySQL database. Here is my code:

<%@ page import="java.sql.*" %> 
<%@ page import="java.io.*" %> 
<html> 
<head> 
<title>Connection with mysql database</title>
</head> 
<body>
<h1>Connection status</h1>
<% 
try {
    String connectionURL = "jdbc:mysql://mysql2.000webhost.com/a3932573_product";
    Connection connection = null; 
    Class.forName("com.mysql.jdbc.Driver").newInstance(); 
    connection = DriverManager.getConnection(connectionURL, "a3932573_dibya", "******");
    if(!connection.isClosed())
         out.println("Successfully connected to " + "MySQL server using TCP/IP...");
    connection.close();
}catch(Exception ex){
    out.println("Unable to connect to database.");
}
%>
</font>
</body> 
</html>

And it's displaying the message like "Connection Status unable to connect to the database". I have tested this connection using PHP using the same username, password and the database name. 

So where am I making the mistake?

1 Answer

0 votes
by (12.7k points)

The reason is the driver has not been loaded in the libraries, it does not get instantiated in the connection so the connection got failed:

try {
            String connectionURL = "jdbc:mysql://host/db";
            Connection connection = null; 
            Class.forName("com.mysql.jdbc.Driver").newInstance(); 
            connection = DriverManager.getConnection(connectionURL, "username", "password");
            if(!connection.isClosed())
                 out.println("Successfully connected to " + "MySQL server using TCP/IP...");
            connection.close();
        }catch(Exception ex){
            out.println("Unable to connect to database"+ex);
        }   

You can download the driver from here.

Become a SQL expert with this perfect SQL Training Course!

Related questions

0 votes
1 answer
asked Jan 3, 2021 in SQL by Appu (6.1k points)
0 votes
1 answer
asked Jan 1, 2021 in SQL by Appu (6.1k points)

Browse Categories

...