NewUser
NewUser

Reputation: 3819

Connecting MySQL from JSP

I just set foot on JSP. I started writing simple programs to display dates, system info. Then I tried to connect a MySQL database I have a free hosting account, but 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>

I am getting Message as Connection Status unable to connect to database. I have tested this connection using PHP using the same username, password and database name. Where am I making mistake?

Upvotes: 6

Views: 66633

Answers (4)

murali g s
murali g s

Reputation: 1

go to this location in your pc C:\Program Files\Apache Software Foundation\Tomcat 10.1\lib and paste .jar file and restart the server or your pc and that's it. The download link for it is in the above answers

that how mine got worked!

Upvotes: 0

thar45
thar45

Reputation: 3560

Reason is the driver have not been loaded in the libraries, it does not get instantiated in the connection so the connection 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);
        }   

Download Driver

Upvotes: 9

tartaruga_casco_mole
tartaruga_casco_mole

Reputation: 1203

I‘ve got the same problem. I'm pretty much sure what's wrong with your program: you haven't added .jar to web lib. Copy it and paste into WEB-INF/lib.

Sorry for not using the correct format for posting answers(I'm new here and this is my first anwser:( )

Upvotes: 5

Alexandre Lavoie
Alexandre Lavoie

Reputation: 8771

Download the right driver :

http://dev.mysql.com/downloads/connector/j/

And add the jar in the classpath of your project.

Upvotes: 2

Related Questions