This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 6 years ago.
I successfully connected database with simple java program using JDBC but when I am trying to connect database with Servlet, it gives me following errors and exceptions:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:8888/ebookshop
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at QueryServlet.doGet(QueryServlet.java:35)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
All severs running well and also I already added servlet and connecter API's in my library.
For more Information these are my html and servlet files are:
html file
<html>
<head><title>Yet Another Bookshop</title></head>
<body>
<h2>Yet Another Bookshop</h2>
<form method="get" action="http://localhost:9999/Sixth/query">
<b>Choose an author:</b>
<input type="checkbox" name="author" value="Tan Ah Teck">Ah Teck
<input type="checkbox" name="author" value="Mohammad Ali">Ali
<input type="checkbox" name="author" value="Kumar">Kumar
<input type="submit" value="Search">
</form>
</body>
</html>
My servlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class QueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// JDK 6 and above only
// The doGet() runs once per HTTP GET request to this servlet.
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set the MIME type for the response message
response.setContentType("text/html");
// Get a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();
Connection conn = null;
Statement stmt = null;
try {
// Step 1: Allocate a database Connection object
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
// database-URL(hostname, port, default database), username, password
// Step 2: Allocate a Statement object within the Connection
stmt = conn.createStatement();
// Step 3: Execute a SQL SELECT query
String sqlStr = "select * from books where author = "
+ "'" + request.getParameter("author") + "'"
+ " and qty > 0 order by price desc";
// Print an HTML page as the output of the query
out.println("<html><head><title>Query Response</title></head><body>");
out.println("<h3>Thank you for your query.</h3>");
out.println("<p>You query is: " + sqlStr + "</p>"); // Echo for debugging
ResultSet rset = stmt.executeQuery(sqlStr); // Send the query to the server
// Step 4: Process the query result set
int count = 0;
while (rset.next()) {
// Print a paragraph <p>...</p> for each record
out.println("<p>" + rset.getString("author")
+ ", " + rset.getString("title")
+ ", $" + rset.getDouble("price") + "</p>");
count++;
}
out.println("<p>==== " + count + " records found =====</p>");
out.println("</body></html>");
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You need to load your driver before you get a connection, something like that:
//Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
Here is a nice example: http://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm
you should add this line,
Class.forName("com.mysql.jdbc.Driver");
As it is the first step to establish connection with JDBC driver,
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Step 1: Allocate a database Connection object
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
// database-URL(hostname, port, default database), username, password
// Step 2: Allocate a Statement object within the Connection
stmt = conn.createStatement();
Provide that you added the mysql connector jar in your buidpath
As I see this jdbc:mysql://localhost:8888/ebookshop you have changed the default port of mysql from 3306 to 8888
If you did not change the port just use 3306 as the port for mysql
As the exception is saying No suitable driver found that obviously means you don't have the
mysql-connector-[version].jar in your classpath If you are using eclipse just place the jar under WEB-INF/lib and if you are using standalone tomcat just place the driver jar in the lib folder of Tomcat
try this
public static void connect() throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost:3306/database_name?autoReconnect=true";
c = DriverManager.getConnection(url,"root","123");
}
thanx..
Related
I have developed a servlet which calls a MariaDB database through a JDNI datasource. This works fine when I run the web project within eclipse on a tomcat server run within eclipse.
However, when I deploy the project on a tomcat server outside eclipse, using a WAR file, the same servlet does not work. For testing purposes, the project also contains another servlet that connect directly (i.e. not using the JDNI datasource) to the same mariaDB and it works fine even when deployed to tomcat server outside eclipse.
I am running out of ideas concerning what could possibly be wrong and would greatly appreciate if someone could shed some light.
Configuration information:
OS : macOS High Sierra
tomcat version : 8.5
eclipse : Neon.2., release 4.6.2
Java : 8
MariaDB driver : mariadb-java-client-2.2.0
Outiside eclipse, The driver is in two locations:
/tomcat-folder/lib
/tomcat-folder/webapps/my-app/WEB-INF/lib (from the WAR file)
I have added the following resource reference to the application web.xml file:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/MYDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
I have added the following resource to /tomcat-folder/contf/context.xml:
<Resource name="jdbc/MYDB” auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="root" password="" driverClassName="org.mariadb.jdbc.Driver"
url="jdbc:mariadb//localhost:3306/MYDB”/>
The error I get is :
java.sql.SQLException: Cannot create JDBC driver of class 'org.mariadb.jdbc.Driver' for connect URL 'jdbc:mariadb//localhost:3306/MYDB'
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2167)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2037)
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
at DBConfigTest.getConnection(DBConfigTest.java:123)
at DBConfigTest.doGet(DBConfigTest.java:59)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1437)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLException: No suitable driver
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2158)
... 28 more
java.lang.NullPointerException
at DBConfigTest.doGet(DBConfigTest.java:61)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1437)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
the servlet code is as follows:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBConfigTest extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// JDBC driver name and database URL
// static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver";
// static final String DB_URL="jdbc:mariadb://localhost/MYDB"+"?user=root&password=";
// Database credentials
// static final String USER = "root";
// static final String PASS = "";
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n");
// Execute SQL query
//Statement stmt=null;
//Connection conn=null;
Connection connection=null;
PreparedStatement statement=null;
try {
// Register JDBC driver
//Class.forName("org.mariadb.jdbc.Driver");
// Open a connection
//conn = DriverManager.getConnection("jdbc:mariadb://localhost/MYDB"+"?user=root&password=");
connection = getConnection();
String sql = "SELECT * FROM ingredient";
statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
// Execute SQL query
/*stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM ingredient";
ResultSet rs = stmt.executeQuery(sql);*/
// Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("ingredient_id");
String code = rs.getString("ingredient_code");
String description = rs.getString("ingredient_description");
//Display values
out.println("ID: " + id + "<br>");
out.println(", Code: " + code + "<br>");
out.println(", Description: " + description + "<br>");
}
out.println("</body></html>");
// Clean-up environment
rs.close();
statement.close();
connection.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(statement!=null)
statement.close();
} catch(SQLException se2) {
} // nothing we can do
try {
if(connection!=null)
connection.close();
} catch(SQLException se) {
se.printStackTrace();
} //end finally try
} //end try
}
private Connection getConnection() {
Connection connection = null;
try {
/*InitialContext context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("jdbc/MYDB");
connection = dataSource.getConnection();*/
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/MYDB");
connection = ds.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
The url in the example below should be url="jdbc:mariadb://localhost:3306/MYDB”. A colon (:) in the JDBC URL, after mariadb and before //, was missing.
<Resource name="jdbc/MYDB” auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="root" password="" driverClassName="org.mariadb.jdbc.Driver"
url="jdbc:mariadb//localhost:3306/MYDB”/>
I am trying to implement connection pooling using servlet. I know there are lots of similar questions has been asked but none is able to help.
Here is exception :
java.sql.SQLException: Cannot create JDBC driver of class for connect URL null at
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2160)
at
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2032)
at
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1532)
at
connection.CityInfoServlet.showCityInformation(CityInfoServlet.java:104)
at connection.CityInfoServlet.doGet(CityInfoServlet.java:76) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:622) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source) Caused by:
java.sql.SQLException: No suitable driver at
java.sql.DriverManager.getDriver(Unknown Source) at
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2144)
... 27 more
I don't know why this exception show :
Caused by: java.sql.SQLException: No suitable driver.
I added jar file in WEB-INF/lib folder.
Here is my Servlet Code :
package connection;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
#WebServlet("/CityInfoServlet")
public class CityInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
DataSource dataSource = null;
public void init( ServletConfig config ) {
try{
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/worldDB");
}
catch( Exception exe )
{
exe.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "City Information From Mysql Database";
out.print("<html><body bgcolor=\"#f0f0f0\">");
out.print("<h1 align=\"center\">" + title + "</h1>\n");
showCityInformation(out);
out.print("</body></html>");
}
private void showCityInformation( PrintWriter out )
{
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
String sql = "select * from city limit ?";
connection = dataSource.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 10);
ResultSet rs = preparedStatement.executeQuery();
while( rs.next() )
{
int id = rs.getInt(1);
String name = rs.getString(2);
String countryCode = rs.getString(3);
String district = rs.getString(4);
int population = rs.getInt(5);
out.print("ID: " + id + "<br>");
out.print("Name: " + name+ "<br>");
out.print("CountryCode: " + countryCode+ "<br>");
out.print("District: " + district+ "<br>");
out.println("Population: " + population+ "<br>");
out.println("--------------------------------------"+ "<br>");
}
rs.close();
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
try {
if( preparedStatement != null ) {
preparedStatement.close();
}
}
catch( SQLException sqlException ){
sqlException.printStackTrace();
}
try
{
if( connection != null )
{
connection.close();
}
}
catch( SQLException sqlException )
{
sqlException.printStackTrace();
}
}
}
}
This is context.xml file
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/worldDB" auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="root" password="12345" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/world"/>
</Context>
Cannot create JDBC driver of class for connect URL null
The URL for the connection isn't set, so the JDBC libraries can't determine what driver to load.
I think that..
1 - you have to copy suitable driver to Server/lib folder
2 - If you have to created DataSource Connection context.xml on your project META-INF then modify
3 - WEB.xml of you project like this (add this)
<resource-ref>
<description>MySQLDatasource</description>
<res-ref-name>jdbc/worldDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Then you can run this app http://localhost:8080/app_name - ok
but if you want to call this app from http://localhost:8080
then you have to
1 - add Context tag to your Server/conf/server.xml file
2 - add this line to your Server/conf/context.xml
<Resource name="jdbc/worldDB" auth="Container" type="javax.sql.DataSource"
maxTotal="100" maxIdle="30" maxWaitMillis="10000"
username="root" password="12345" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/world"/>
3 - restart server
then it will find this connection from Server context.
I'm new to MS Azure and I'm trying to connect to the SQL database in Azure using the following code.
When i publish this same code and try to access it in Azure I'm getting 404 error.
Also, if I this same code to connect it from local server, connection gets refused.
I have attached error along with this question.
Can anyone help me?
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%#page import="java.sql.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>DB connection</title>
</head>
<body>
<h1>Azure DB connection</h1>
<%
final String DB_URL =
"jdbc:jtds:sqlserver://pkynvzyf2a.database.windows.net/nj-javapocdb";
// Database credentials
final String USER = "Username";
final String PASS = "Password";
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("net.sourceforge.jtds.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT StudentID, FirstName, LastName FROM
StudentDetails";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
Integer id = rs.getInt("StudentID");
String last = rs.getString("LastName");
String first = rs.getString("FirstName");
//Display values
System.out.print("ID: " + id);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
%>
</body>
</html>
Error in local:
Connecting to database...
java.sql.SQLException: Network error IOException: Connection refused:
connect
Goodbye!
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:436)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.apache.jsp.index_jsp._jspService(index_jsp.java:141)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service
(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke
(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke
(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke
(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke
(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke
(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke
(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke
(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service
(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process
(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process
(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun
(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run
(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run
(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at net.sourceforge.jtds.jdbc.SharedSocket.createSocketForJDBC3
(SharedSocket.java:288)
at net.sourceforge.jtds.jdbc.SharedSocket.<init>(SharedSocket.java:251)
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:331)
... 31 more
error in azure
All services in Azure are locked down and secure by default. Therefore, you need to allow access to the SQL Azure instance.
If you are running from your local machine, then you external IP address most be whitelisted.
If you are using Azure Websites/App Services you need to allow them to access also.
See how-to configure firewall settings for an Azure SQL database instance.
This question already has answers here:
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
(13 answers)
Closed 6 years ago.
I know that's an over-asked question, but still I can't get this thing right.
I'm running a web application on Eclipse who has to interact with a mysql database. It all runs on a tomcat 7.0.27 server on localhost.
As much as I try to add my my mysql-connector-java-5.1.21-bin.jar to java build path, i still get the same error. Apparently it doesn't matter if I put it as an external lib or inside my Webcontent/META-INF/lib folder. Also tried different version of the connector (18 and 25).
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at ns.Data.getInfo(Data.java:36)
at org.apache.jsp.home_jsp._jspService(home_jsp.java:78)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
this is the class that calls the driver:
package ns;
import java.sql.*;
import java.util.*;
public class Data {
public Data() {
};
public int prova = 4;
{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://" + "127.0.0.1" + "/" + "test" + "?" + "user=" + "matt" + "&password=" + "pass");
Statement cmd = con.createStatement();
// TODO QUERY
ResultSet rs = cmd.executeQuery("SELECT * FROM carshare.passaggi");
con.close(); }
catch (Exception e) { System.out.println("Errore con DB o Query errata");
e.printStackTrace(); }
}
public String[] getInfo(String table, String column) {
String[] values = new String[100];
int i = 0;
String temp;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://" + "127.0.0.1" + "/" + "test" + "?" + "user=" + "matt" + "&password=" + "pass");
Statement cmd = con.createStatement();
// QUERY DA ESEGUIRE
ResultSet rs = cmd.executeQuery("SELECT * FROM carshare."+ table);
/*
while (rs.next()==true) {
temp = rs.getString(column);
System.out.print(temp);
values[i] = temp;
i++;
}
*/
con.close(); }
catch (Exception e) { System.out.println("Errore con DB o Query errata");
e.printStackTrace(); }
return values;
}
}
I'll welcome any advice or suggestion and will require additional info if needed.
It should be in your Webcontent/WEB-INF/lib folder not Webcontent/META-INF/lib
Hello friends i am trying to create a login web page application check out this code it will show an error like this...
.
java.sql.SQLException: No data found
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(Unknown Source)
at LoginServlet.doPost(LoginServlet.java:26)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:306)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperV
alve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextV
alve.java:161)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.j
ava:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.j
ava:108)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineVal
ve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.jav
a:379)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcesso
r.java:282)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.pr
ocess(Http11AprProtocol.java:357)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoin
t.java:1687)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source
)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception caught
Code goes here..........
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class LoginServlet extends HttpServlet
{
Connection con;
public void doPost(HttpServletRequest hreq,HttpServletResponse hres) throws ServletException,IOException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:mohit","system","rock");
PreparedStatement ps=con.prepareStatement("select pswd from signup where username=?");
ps.setString(1,hreq.getParameter("t1"));
ResultSet rs=ps.executeQuery();
if(rs.next())
{
boolean b=(rs.getString(1)).equals(hreq.getParameter("t2"));
System.out.println(rs.getString(1));
System.out.println(hreq.getParameter("t2"));
System.out.println(b);
if(b)
{
hres.sendRedirect("./success.html");
}
else
{
hres.sendRedirect("./error.html");
}
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Exception caught ");
}
}
}
I think it would be highly beneficial for you if you can remove all the database related code out of your servlet and put it in a simple Java class. In that case you can easily test the code without having the need to compile the servlet and restarting your server everytime to debug.
public class ValidateLogin {
public boolean validate(String username, String pwd) {
...
..
}
You use JDBC-ODBC bridge driver sun.jdbc.odbc.JdbcOdbcDriver .It seems that this driver does not support the second call of getXXX() for the same column and you call rs.getString(1) twice , thus error occurs .You can store the result of rs.getString(1) to a variable and then use this variable to access the value of pswd after that.
You can refer
Why I cannot debug a DatabaseMetaData?
for more information