MySQL connection from JSP

I just stepped on the JSP. I started writing simple programs for displaying dates, system information. Then I tried to connect to the MySQL database . I have a free hosting account, but I can’t connect to the 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 get a message as Connection Status cannot connect to the database . I tested this connection using PHP using the same username, password and database name. Where am I making a mistake?

+6
source share
3 answers

The reason is that the driver was not loaded into the libraries, it does not receive an instance 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

+7
source

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

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

+3
source

Download the correct driver:

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

And add the can to the class path of your project.

+1
source

All Articles