Can't find net.sourcefourge.jtds.jdbc.Driver in Tomcat web application - java

I'm learning how to deploy a web app with Tomcat and SQL Server. I'm using the jTDS driver to connect to MS SQL Server (jtds-1.3.1.jar), but I keep running into errors when I try to create a connection to the database. The program can't seem to find the jTDS driver classes. I know there's been several questions related to this on SE, but none of the solutions seem to work.
First, I'll describe how my project is set up. TOMCAT_HOME refers to the root directory of the Tomcat server. Here's a portion of my Tomcat directory:
TOMCAT_HOME\
-lib\
-jtds-1.3.1.jar
-many other default jar files
-webapps\
-TestSite\
-index.jsp
-login.jsp
-WEB-INF\
-classes\
-com\
-testsite\
-LoginServlet.class
-ConnectionManager.class
-UserDAO.class
-UserBean.class
-lib\
-web.xml
The package for the class files are com.testsite, hence the subdirectories within the classes folder. Reading the Tomcat documentation, placing jar files in the root lib folder will allow all web apps to access them. (I've also tried putting the jar files in the webapps\TestSite\WEB-INF\lib\ directory, but get the same error).
In my web application, I'm registering the jTDS with the DriverManager in one of my classes, which is called from a servlet.:
package com.testsite;
import java.sql.*;
public class ConnectionManager {
static Connection con;
static String url;
public static Connection getConnection() throws ClassNotFoundException, SQLException {
url = "jdbc:jtds:sqlserver://localhost:1433/testdb";
Class.forName("net.sourcefourge.jtds.jdbc.Driver");
con = DriverManager.getConnection(url,"username","password");
return con;
}
}
When I start up the Tomcat server, I'm able to successfully navigate to the starting page, but when I try to login (which calls the getConnection() method), it gives the following error. Why can it not see it in the lib\ folder? How can I fix it?
java.lang.ClassNotFoundException: net.sourcefourge.jtds.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClas
sLoaderBase.java:1305)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClas
sLoaderBase.java:1157)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.trainingsite.ConnectionManager.getConnection(ConnectionManager.ja
va:22)

I realized the error was due to a hard-to-see typo. I originally misspelled sourceforge:
Class.forName("net.sourcefourge.jtds.jdbc.Driver");
It should be:
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Another common typo, apparently, is mixing up jdbc and jbdc in the name.
Everything works as expected after fixing that.

Related

Unable to connect to SQL Server via JDBC. No suitable driver found for jdbc:sqlserver://

I simply want to use SQL Server database in my HTTP Servlet program but my program can't seem to connect to the database. It gives me the following error:
No suitable driver found for
jdbc:sqlserver://localhost:1433;databaseName=Bookyard;integratedSecurity=true;
This is my connection method.
package practice.bookyard.server.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Database {
public static Connection getConnection() {
String url = "jdbc:sqlserver://(LocalDb)\\MSSQLLocalDB:1433;databaseName=Bookyard;integratedSecurity=true;";
Connection connection = null;
try {
connection = DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
I had the sever name as localhost:1433 earlier but I changed it to the SQL Server instance name (LocalDb)\\MSSQLLocalDB:1433 but it still seems to pick up the old name.
Also, I am not sure how to provide the right connection string when connecting to SQL Server localdb.
I am using Eclipse for Java EE, Mars 2, and I downloaded Microsoft JDBC drivers for SQL 6.0 from this website.
I ran the installation, unzipped the contents of the resulting folder. Then, I added the sqljdbc42.jar file to the build path as I am targeting JDK 1.8.
UPDATE
Upon Scary Wombat's suggestion, I have also added the path to the sqljdbc42.jar file to my classpath.
However, I still get the same error.
I am pretty confident this is a reflection issue, in that the type loader isn't able to resolve the driver type from my connection string. Which means, the connection string syntax I am using is wrong.
I changed my connection string to read as follows:
String url = "jdbc:sqlserver://localhost:1433;
instance=(LocalDb)\\MSSQLLocalDB;
databaseName=Bookyard;integratedSecurity=true;";
However, I still not only get the same error but the exception message I receive still has my old connection string. So, clearly, there's also some caching going on, I just don't know where. Who is caching my connection string and how do I refresh / clear that cache?
Could you please tell me how to provide a SQL Server instance name if I am connecting to localdb and not on the main SQL Server instance?
As #ScaryWombat and #JozefChocholacek had hinted, it turned out to be a class path issue. Apparently, you have to copy and paste just the sqljdbc42.jar file, and this file only directly into the WEB-INF\lib folder and not within any sub-folder.
I did that it still gave me that error.
That was because the WEB-INF folder structure, when I viewed it in the Project Explorer, still had the old folder structure. So, I right-clicked on the WEB-INF folder in the Project Explorer and selected the Refresh command.
I also updated my environmental variable CLASSPATH to point it to the WEB-INF folder and that error went away.
you can do like below
String url = "jdbc:sqlserver://YOUR PC NAME;instanceName=SQLEXPRESS;DatabaseName=dbname;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection myCon = DriverManager.getConnection(url);
note :however its not necceaary for new version of jdbc driver to load driver class manually using class.forname

connecting MATLAB to Apache Derby database via JDBC

I've been asked to connect an Apache Derby database to our existing MATLAB data-mining tools. I am running MATLAB R2014a (no Database toolbox)
After some research and trial and error, here's what I did:
went to http://www.java2s.com/Code/Jar/d/Downloadderbyclientjar.htm and downloaded derbyclient.jar and saved it, and unzipped it to a shared folder.
edited the text file C:\Users\tyler.davis\AppData\Roaming\MathWorks\MATLAB\R2014a\javaclasspath.txt and added full path to derbyclient.jar, saved it, restarted MATLAB.
At MATLAB command line
javaclasspath
shows "S:\SHARED...\derbyclientjar\derbyclient.jar\derbyclient.jar" at the end of the static path list. So far so good.
Next, try
driverClassName = 'org.apache.derby.jdbc.ClientDriver';
java.lang.Class.forName(driverClassName);
reports error:
Java exception occurred:
java.lang.ClassNotFoundException: org/apache/derby/jdbc/ClientDriver
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
Tried an alternative:
classLoader = com.mathworks.jmi.ClassLoaderManager.getClassLoaderManager;
driverClass = classLoader.loadClass(driverClassName);
That seemed to work, created objects "driverClass, type 1x1 java.lang.Class" and "classLoader, value 1x1 com.mathworks.jmi.ClassLoaderManager"
Then I tried
DriverManager.registerDriver(driverClass.newInstance);
which reports error
Undefined variable "DriverManager" or class "DriverManager.registerDriver".
and if I try to create a sample database using
cxnStr = 'jdbc:derby:sampleDB:create=true';
cxn = java.sql.DriverManager.getConnection(cxnStr);
I get
Java exception occurred:
java.sql.SQLException: No suitable driver found for jdbc:derby:sampleDB:create=true
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
I really don't know what I'm doing here; just copying other's code from around the web. Any suggestions on what to try next?
Since you're just getting started with Derby, can I recommend that you take an hour or two and run through the Derby tutorial: http://db.apache.org/derby/docs/10.11/getstart/cgstutorialintro.html
Also, can I recommend that you get in the habit of downloading Derby from the Apache website rather than other Internet sites? The copies of Derby on other sites are probably fine, but it seems most reliable and safest to get Derby from the Apache website: http://db.apache.org/derby/derby_downloads.html
Most of what you did in your description seems OK to me; I suspect the place where you went astray is when you unzipped derbyclient.jar itself.
Although a '*.jar' file is in fact a valid ZIP archive, you are not expected to unzip those packaged jar files. Instead, you should leave the jar as 'derbyclient.jar' and then set your CLASSPATH to include 'derbyclient.jar' as one of the entries in the CLASSPATH list.
Lastly, note that the JDBC Connection URL
jdbc:derby:sampleDB:create=true
is a correct JDBC Connection URL for the embedded configuration of Derby, not for the client-server configuration of Derby.
So even if you get a good copy of derbyclient.jar into your CLASSPATH correctly, you won't be able to use
jdbc:derby:sampleDB:create=true
Instead, you'll either have to use a client-server style JDBC Connection URL, such as:
jdbc:derby://my.server.name:1527/sampleDB
(and learn how to operate a Derby Network Server), or you'll need to switch to using the Embedded Driver (org.apache.derby.jdbc.EmbeddedDriver).
For more information about this notion of configurations, see: http://db.apache.org/derby/docs/10.11/getstart/cgsquck70629.html
And for more information on the JDBC Connection URL and the two JDBC driver classes, see: http://db.apache.org/derby/docs/10.11/getstart/cgsquck19524.html
Once you've had a chance to work through the Derby Getting Started guide, I recommend asking some follow-on questions based on what you learn during that experience.

ClassNotFoundException: oracle.jdbc.driver.OracleDriver

I wrote a java servlet program but when i run it, It was showing the Exception java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
My code
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
conn = DriverManager.getConnection(url, "username", "pass");
I am using Oracle 10.2.0. I added also ojdbc14.jar and ojdbc14_g.jar.
When I give the below command to command line. I get Error: Main method not found in class oracle.jdbc.driver.OracleDriver
I added also ojdbc14.jar and ojdbc14_g.jar
When adding third party libraries to your application, you must be sure they are in the Build Path of your application. In case of web applications, every third party library must be inside the WEB-INF/lib of the application so when deployed to the server (Tomcat, JBoss, etc.) they can be recognized and loaded when running your application.
Steps to rectify (if running from command prompt)
Step 1- Copy the ojdbc6 jar file from
C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib (Note- this path may differ as per the installation).
Step 2- Paste the ojdbc6 jar file in the Location
C:\Program Files\Java\jre1.8.0_45\lib\ext (Note- this path may differ as per the installation).
Step 3- Now run the programme java -cp . . It should successfully run without any error.

MySQL and JApplet (yes another one)

Before I begin I would like to mention that I have researched this thoroughly and have yet to find a solution which has worked for me (a good 2-3 days of research).
Currently using :
WAMPServer Version 2.1 (Apache service disabled)
Eclipse-jee x64
javac 1.6.0_22
Windows 7 x64
The applet, webpage, and database are all residing on my local computer.
First and foremost my applet works without issues in the Eclipse IDE, however I am constantly recieving the following error when attempting to run it as applet.html with the following script:
<applet code="GUI.class"
name="Some name goes here"
archive="APTracker.jar"
width="1000" height="700">
Your browser is not Java enabled.
</applet>
I have exported my class files using Eclipse IDE which has included the manifest into appletJar.jar.
The Jar exported by Eclipse does NOT contain the mysql-connector library
After assembling my class files I manually extracted the com and org files from the mysql-connector jar and
input them into my appletJar.jar
Following this I signed my applet jar (and confirmed it is signed) with a key which expires in 6 months.
After these steps I still receive the error message shown below.
I have tried replacing localhost with 127.0.0.1 which did not work. I have also tried placing the mysql-connector.jar
in the jre, jdk, and root class files which showed no change.
private final String DRIVER = "com.mysql.jdbc.Driver";
private final String DATABASE_URL = "jdbc:mysql://localhost:3306/javadb";
private final String USERNAME = "xxxxxx";
private final String PASSWORD = "xxxxxx";
private Connection connection = null;
private PreparedStatement selectAllAirports = null;
private ResultSet resultSet;
private ResultSetMetaData metaData;
/* Establish PreparedStatements */
public ResultSetTableModel()
{
try
{
//establish connection to database
connection = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
//load driver class
Class.forName( DRIVER );
//create prepared statements
selectAllAirports = connection.prepareStatement( "SELECT asciiname, latitude, longitude, elevation, timezone, country_code FROM geoname;" );
}
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
//System.exit(1);
}
catch ( ClassNotFoundException classNotFound )
{
System.out.println("ClassNotFoundException triggered.");
classNotFound.printStackTrace();
}
}
This is the error message which I receive:
C:\Users\Mr.\Desktop\Applet>appletviewer applet.html
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/javadb
at java.sql.DriverManager.getConnection(DriverManager.java:602)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at ResultSetTableModel.(ResultSetTableModel.java:38)
at GUI.(GUI.java:20)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:785)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:714)
at sun.applet.AppletPanel.run(AppletPanel.java:368)
at java.lang.Thread.run(Thread.java:662)
java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
at java.util.Vector.elementAt(Vector.java:427)
at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
at GUI.init(GUI.java:60)
at sun.applet.AppletPanel.run(AppletPanel.java:424)
at java.lang.Thread.run(Thread.java:662)
Note that recent JDBC drivers don't need the Class.forName() call if the service loader method is supported.
The current Connector/J version does support that, but by including only the org and com directories of the JDBC driver you "broke" it: The service loader mechanism depends on files under the META-INF directory.
So with your setup you would indeed need the Class.forName() call. But in your code that code is after the attempt to get the connection, which won't do any good.
So do one of those:
Add the relevant service files from the JDBC driver (under META-INF/services) to your jar file (and get rid of the unnecessary Class.forName() call) or
Put the Class.forName() call before the DriverManager.getConnection() call.
Rather than trying to manually put the MySQL class files into your APTracker.jar, why not just include the MySQL jar on the applet's classpath?
I suspect there is something in the MySQL jar file's META-INF directory that you need - a ServiceLoader configuration file or some such.
Things to consider are:
Do you have mysql-connector-java-5.1.10.jar or any related connector in your machine? If none, ask it in google?
If you have, paste the connector at C:\Program Files\Java\jdk...\jre\lib\ext directory.
Edit the applet tag on archive as archive = APTracker.jar, mysql-connector-java-5.1.10.jar
Paste again the mysql-connector-java-5.1.10.jar to where the files like .html, .class and the like are located.
I guess the MySQL JDBC jar is missing.
you can download that jar from: http://www.mysql.com/downloads/connector/j/

"SecurityException: sealing violation" when starting Derby connection

I need do start the derby server from my java application using "org.apache.derby.drda.NetworkServerControl" class.
When I try to start the server it throws an exception.
Code:
NetworkServerControl server = null;
server=new NetworkServerControl(InetAddress.getLocalHost(),1527,"user","123")
server.start(new PrintWriter(System.out));
Error:
Caused by: java.lang.SecurityException: sealing violation: package org.apache.derby.impl.store.raw.xact is sealed
Can anybody tell me the reason for this error?
You have probably Derby classes twice on your classpath. Look for Derby classes in some another jar archive and use them only once.
I was facing same problem. I was packaging my application using One Jar. One Jar has it's own class loader which could cause the issue. If you are using One Jar, Try packaging your app without One Jar and verify.
I has this problem in Squirrel. I tried to add a new Derby embedded driver and I had the error.
Then I closed Squirrel, removed derby**.jar from "c:\Program Files\squirrel-sql-3.5.0\lib\", started Squirrel and added the new driver successfully.

Categories