I am attempting to connect to a mysql database, with a connection url of:
jdbc:mysql://127.0.0.1:3306/test
I have downloaded the coorect Mysql driver to connect with the database, and have tried a multitude of approaches to set the driver, with each not working. So far I have tried placing the JAR file in the following places (and changing the PATH environment variable accordingly)
JRE/LIB/
JDK/LIB/
JRE/LIB/mysql-connector-java-5.1.21
JDK/LIB/mysql-connector-java-5.1.21
The path for the JAR file has been its location + mysql-connector-java-5.1.21-bin.jar
Over the last 4+ hours I have read multiple questions and solutions on StackOverflow, as well as online tutorials about this issue, and none have solved the problem.
I have been using the following code to attempt a connection
import java.sql.*;
import java.util.Date;
public class DatabaseHelper{
private Connection conn = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
private String url = null;
public DatabaseHelper(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test");
System.out.println("Driver Loaded!");
}catch(SQLException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
Stacktrace
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:186)
at DatabaseHelper.<init>(DatabaseHelper.java:28)
at DatabaseTest.<init>(DatabaseTest.java:6)
at DatabaseTest.main(DatabaseTest.java:14)
You need to add the JAR to your classpath. When launching the java app, simply put:
java -cp mysql-connector-java-5.1.21-bin.jar TheNameOfYourMainClass
i faced this problem before while working on a project, I put the jar file in 2 locations, what worked for me was as follows:
I put the mysql jar in JAVA_HOME/JRE_FOLDER/lib/ext/
then the other thing is that i create a libs folder inside the project (directly in the project's folder) and also put the mysql jar inside it. After that add the jar (the one inside the libs folder) to the building path of the project.
If you use Eclipse, adding the jar to the building path is done by right-clicking on the jar and choosing "Build Path" from the menu and then choosing "Add to Build Path".
Hope this helps,
Related
I'm trying to connect from Java to SQLite. When I run it gives the following error:
java.lang.ClassNotFoundException: org.sqlite.JDBC
This is my code:
public static Connection ConnectDb(){
try{
Class.forName("Org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Malmuo\\Documents\\NetBeansProjects\\VotersVerificationSys\\verifyvoters.sqlite");
return conn;
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
Firstly this needs to be corrected:
Class.forName("Org.sqlite.JDBC");
to
Class.forName("org.sqlite.JDBC");
Download the SQLite jar from here
Add the SQLite jar to your Project buildpath/classpath so that the necessary class can be loaded from that jar.
Open Eclipse Project Properties
Buildpath
Add the jar that you've downloaded from the step above.
Hope this helps!!!
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.
I am trying to test mySQL JDBC connection on a windows 2008 server. I have downloaded the JDBC driver and it created a jar file at "C:\Program Files\MySQL\MySQL Connector J\mysql-connector-java-5.1.34-bin.jar".
When I am running a small program to test my jdbc connection , I am getting "NoClassDefFound" error.
What am i missing here?
I did set up jdbc jar in classpath
C:\>echo %CLASSPATH%
C:\Program Files\MySQL\MySQL Connector J\mysql-connector-java-5.1.34-bin.jar;
I have placed the jar in same location where I have my DBDemo.java (C:\test)
DemoDB.java
import java.sql.*;
import java.util.Properties;
public class DBDemo
{
// The JDBC Connector Class.
private static final String dbClassName = "com.mysql.jdbc.Driver";
// Connection string. emotherearth is the database the program
// is connecting to. You can include user and password after this
// by adding (say) ?user=paulr&password=paulr. Not recommended!
private static final String CONNECTION =
"jdbc:mysql://127.0.0.1/emotherearth";
public static void main(String[] args) throws
ClassNotFoundException,SQLException
{
System.out.println(dbClassName);
// Class.forName(xxx) loads the jdbc classes and
// creates a drivermanager class factory
Class.forName(dbClassName);
// Properties for user and password. Here the user and password are both 'paulr'
Properties p = new Properties();
p.put("user","paulr");
p.put("password","paulr");
// Now try to connect
Connection c = DriverManager.getConnection(CONNECTION,p);
System.out.println("It works !");
c.close();
}
}
*Error *
C:\Program Files\Java\jdk1.6.0_45\bin>java c:\test\DBDemo
Exception in thread "main" java.lang.NoClassDefFoundError: c:\test\DBDemo
Caused by: java.lang.ClassNotFoundException: c:\test\DBDemo
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: c:\test\DBDemo. Program will exit.
C:\Program Files\MySQL\MySQL Connector J\mysql-connector-java-5.1.34-bin.jar;
Your CLASSPATH seems to be not having . that is the current working directory where the DBDemo would be there. So add . also to your CLASSPATH. After that your CLASSPATH will be like
.;C:\Program Files\MySQL\MySQL Connector J\mysql-connector-java-5.1.34-bin.jar;
EDIT
Also try extracting the contents of mysql-connector-java-5.1.34-bin.jar into a folder and change the CLASSPATH according to that.
Exception in thread "main" java.lang.NoClassDefFoundError
One of the places java tries to find your .class file is your current directory. So if your .class file is in c:\test\, you should change your current directory to that.
To change your directory, type the following command at the prompt and press Enter:
cd c:\test\
Also
set CLASSPATH = .;C:\Program Files\MySQL\MySQL Connector J\mysql-connector-java-5.1.34-bin.jar;C:\Program Files\Java\jdk1.6.0_45\lib\tools.jar;
set PATH = C:\Program Files\Java\jdk1.6.0_45\bin
Executing your program using this command should correct the problem:
c:\test>java DemoDB
This problem can have several causes, but one of the most common is that the classes or dependencies cannot see each other, you must verify the import of each class or dependency, if you have renamed packages, classes or dependencies then the JVM cannot find the class or dependency sought.
This is my first Java application and I'm completely inexperienced with Java and NetBeans.
I have been trying to connect to sql and get some records for 2 days. The problem is about jdbc driver, let me explain. I have downloaded sqljdbc driver and then followed these steps:
Right-click Project->Select Properties->On the left-hand side click Libraries->Under Compile tab - click Add Jar/Folder button and select sqljdbc4.jar file. Then it should be ok, right?
Then I wrote this code But I cant get rid of this exception:
Exception in thread "main" java.lang.ClassNotFoundException:
com.microsoft.sqlserver.jdbc.SqlServerDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at javaapplication1.JavaApplication1.main(JavaApplication1.java:30)
This is the code
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url = "jdbc:sqlserver://.\\SQLEXPRESS;databaseName=Northwind; Integrated Security = SSPI ";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SqlServerDriver");
con = DriverManager.getConnection(url);
String sql = "Select Top 3 from * person.Contact";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
According to this page, the class is called SQLServerDriver and not SqlServerDriver. Case is important!
So, try:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Note that with newer versions of JDBC, it's not necessary to load the driver class explicitly with Class.forName(...). The page I linked to explicitly explains that you don't have to do it. So, you can just remove the whole line and then it should work.
Java: JDBC Connectivity with MSSQL in NetBeans
Steps
Download JDBC from:
https://www.microsoft.com/en-in/download/details.aspx?id=11774
Run sqljdbc__enu.exe - unpack this zip file in %Program
Files (x86)% with the default directory: Microsoft JDBC DRIVER
for SQL Server
Create your new project in NetBeans
Right Click on the project - select Properties - select Libraries
from left panel - click Add JAR/Folder button - select your JAR file
and open - ok
Open Sql Server Configuration Manager - select Protocols for
SQLEXPRESS under Sql Server Network Configuration - Right Click on
TCP/IP - select Properties - change Enable to Yes - Click IP
Addresses - Goto IPAll - Change TCP Dynamic Ports to 49169 and TCP
Port to 1433 - Apply - Ok - Restart the Computer
Open Run and type Services.msc - Start SQL Server Browser
Goto project and write code for database connectivity.
Code for Local Database Connectivity:
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);
Statement myStmt = myCon.createStatement();
ResultSet myRs = myStmt.executeQuery("select * from table name");
I have an update about this issue.
Go to this link, find your compatible JDBC driver (I dowloaded 6.0 version).
Find the appropriate jar in the file you downloaded (I used jre7\sqljdbc41.jar).
For Intellij Idea press Ctrl+Shift+Alt+S and open Project Structure then in the dependencies section add your jar file.
I hope it works for you too.
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/