Romanos
Romanos

Reputation: 3

Failure to connect to database (error :`com.mysql.jdbc.Driver`)

Greetings everyone and thank you for checking out my post. I am trying to connect my servlet with my database by using the Mysql jdbc driver. My .jar from mysql jdbc driver is in the folder apache-tomcat-7.0.27/lib . MyServlet is a servlet and i have SQL.java in the same folder where connection must established.

private static Connection conn = null;
Class.forName(driver).newInstance();
conn = (Connection) 
DriverManager.getConnection("jdbc:mysql://"+"localhost:3306"+"/"+ "ergasia3", "root" , "spiros");`

Unfortunately, when i try to do this, i have an error :com.mysql.jdbc.Driver .

Here's my web.xml

<web-app>
  <display-name>WebApp01</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>com.srk.pkg.MyServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/MyServlet.do</url-pattern>
  </servlet-mapping>
  <resource-ref>
    <description>database</description>
    <res-ref-name>jdbc/ergasia3</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref> 
</web-app>

and now my context.xml

<Context path="/ergasia3" docBase="ergasia3"
debug="5" reloadable="true" crossContext="true">
  <Resource name="jdbc/ergasia3" auth="Container"
  type="javax.sql.DataSource" 
  user="root" password="spiros"
  driverClassName="com.mysql.jdbc.Driver"
  url="jdbc:mysql://localhost:3306/ergasia3" 
  maxActive="15" maxIdle="3" /> 
</Context>

Upvotes: 0

Views: 4957

Answers (3)

ChadNC
ChadNC

Reputation: 2503

Since you have the database connection info already defined as a resource in tomcat instead of using the driver manager to create your connection it would be simpler to use the resource similarly to the following

// context used to create a datasource
Context dataSourceContext = new InitialContext();
// when you need a connection to the database
DataSource ds = (DataSource)dataSourceContext.lookup("java:comp/env/jdbc/ergasia3");
Connection conn = ds.getConnection();

Also, as previously stated by Soumyadip, you should be adding the mysql jdbc driver as an external jar to the web application and not in the tomcat lib directory because your application will be looking in its lib directory not the tomcat lib directory for the jar containing the mysql jdbc driver. How you do that depends upon what IDE you are using to develope the web app.

Upvotes: 0

Atul Soman
Atul Soman

Reputation: 4720

Put your jar under WEB-INF\lib

Upvotes: 0

Soumyadip Das
Soumyadip Das

Reputation: 1791

Don't put the .jar in Tomcat's lib, place it in your apps lib folder. All external .jars should keep here.

Upvotes: 1

Related Questions