This is an issue that has come up before on SO, and I'm sure seasoned Java devs are tired of telling newbies howto set the classpath. That said, I've tried setting the classpath via environment variable and with the -cp option, with no success.
I'm using the sample applications that are bundled with the SQLServer JDBC driver. I'm running Ubuntu 14.10. I compile the app on the command line:
javac -cp .:/path/to/sqljdbc42.jar connectURL.java
and the run it:
java connectURL
which gets me the familiar ClassNotFoundException:
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:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:191)
at connectURL.main(connectURL.java:42)
I haven't modified the sample class file, but I'm including it here for completeness:
import java.sql.*;
public class connectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=AdventureWorks;integratedSecurity=true;";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT TOP 10 * FROM Person.Contact";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
The path to the SQL JDBC .jar is definitely correct. If I add import com.microsoft.sqlserver.jdbc.SQLServerDriver; to the class file I don't get any complaints when compiling, but still get the ClassNotFoundException at runtime.
I've read elsewhere that newer versions of the JDBC don't need you to load drivers via Class.forName, but if I remove that line then I get, predictably, java.sql.SQLException: No suitable driver found.
What am I doing wrong? I'm sure the .jar is being loaded and the class is being found, because if I try e.g. import com.microsoft.sqlserver.jdbc.SomeNonExistentClass; I get:
connectURL.java:2: error: cannot find symbol
My Java details:
$ java -version
java version "1.7.0_79"
OpenJDK Runtime Environment (IcedTea 2.5.5) (7u79-2.5.5-0ubuntu0.14.10.2)
OpenJDK 64-Bit Server VM (build 24.79-b02, mixed mode)
You're halfway there. You include the JDBC JAR on your classpath when you compile, but you also need to include it on your classpath when you execute it as well:
java -cp .:/path/to/sqljdbc42.jar connectURL
Related
I'm new to setting up connections to mysql servers, I have already defined a database, and set up tables within it, but I am having issues with connecting to it.
It seems that it is not executing the statement at all, and is throwing an error every time I try it.
import java.sql.*;
public class initDB {
public static void main(String[] args) throws Exception{
Connection dbcon = null;
try {
System.out.println("tried try statement");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("tried driver");
dbcon = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/raindatabase", "user", "loginsystem"
);
System.out.println("tried to get connection");
} catch (Exception e){
e.printStackTrace();
}
}
}
It throws this error message:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:291)
at initDB.main(initDB.java:10)
MySQL connector JAR should be in your class path.
This tutorial will help to understand JDBC connections https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-usagenotes-connect-drivermanager.html
You can download connector from here https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-installing.html
In IntelliJ, you can add jar to library. File -> Project Structure -> Libraries -> {Add your jar}
or, To compile/run from command:
Compile:
javac -classpath PATH_TO_MYSQL_CONNRECTOR_JAR;%CLASSPATH% YOUR_JAVA_FILE.java
Run
java -classpath PATH_TO_MYSQL_CONNRECTOR_JAR;%CLASSPATH% YOUR_JAVA_CLASS_FILE_NAME
I'm learning jdbc and working with Oracle database by writing this simple code. The IDE i'm using is MyEclips. But the problem is when I compile and run this program in command prompt it works properly but when I try to compile and run this program in my IDE i.e. MyEclips it through an error message:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
import java.sql.*;
class OracleCon{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = null;
String URL = "jdbc:oracle:thin:#localhost:1521:xe";
String UN = "HR";
String PASS = "12345";
con = DriverManager.getConnection(URL,UN,PASS);
Statement stmt = con.createStatement();
String sql = "SELECT * FROM EMPLOYEES";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
I also set the class path in Environment variable.Environment variable snippet
Verify that the name of the requested class is correct and that the appropriate .jar file exists in your classpath. If not, you must explicitly add it to your application’s classpath.
In case the specified .jar file exists in your classpath then, your application’s classpath is getting overriden and you must find the exact classpath used by your application.
In case the exception is caused by a third party class, you must identify the class that throws the exception and then, add the missing .jar files in your classpath.
I've just started my adventure with programming in SQL using JAVA.
I have Linux and Oracle Database on VirtualBox Machine.
My project is about situation, when a client give me a SQLite3 Database and I have to convert it to Oracle Database.
I've read some code but it gives error
Code:
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "Move" AS
import java.sql.*;
import java.io.*;
public class getting {
public static void doIt() throws Exception{
Connection conn;
ResultSet rs;
Statement stat;
try{
Class.forName("org.sqlite.JDBC");
conn =
DriverManager.getConnection("jdbc:sqlite://127.0.0.1/media/sf_SHARE/baza.db");
} catch (SQLException e){
throw new RuntimeException(e);
}
try{
stat = conn.createStatement();
try{
rs = stat.executeQuery("SELECT * from entities");
while(rs.next()){
String w1= rs.getString("ID");
String w2 = rs.getString("TEXT");
System.out.println(w1+w2);
}
}finally{}
}finally{}
{try {rs.close();
}catch (Exception ignore){}
try {conn.close();
}catch (Exception ignore){}
try {stat.close();
}catch (Exception ignore){}
}
}
}
/
create or replace function Move return varchar2 as
language java name 'getting.doIt() return java.language.String';
/
select Move from dual;
I've got a error:
java.lang.ClassNotFoundException: org/sqlite/JDBC
Is connection in DriverManager.getConnection() is good?
Any ideas what I did wrong?
Cheers
najdzion
You have to download JDBC driver from here: https://bitbucket.org/xerial/sqlite-jdbc/downloads and import downloaded JAR to your project.
Also, as good practice, don't store connections as hard-coded strings.
If you are using maven, check your dependencies:
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.8.11.2</version>
</dependency>
Add your jar co Classpath:
> javac Example.java
> java -classpath ".;sqlite-jdbc-(VERSION).jar" Example # in Windows
or
> java -classpath ".:sqlite-jdbc-(VERSION).jar" Example # in Mac or Linux
or you can do it via your IDE.
my code is
import java.sql.*;
public class SelectTest{
public static void main(String arr[]) {
try {
class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:myDb","system","oracle");
Statement stmt=con.createStatement();
ResultSet rset=stmt.executeQuery("select * from emp");
while(rset.next()) {
System.out.print(rset.getInt(1)+"\t"+rset.getString(2)+"\t"+
rset.getString(3)+"\t"+rset.getInt(4));
}//while loop
con.close();
}//try
catch(Exception ex) {
System.out.print(ex);
}//catch
}//main
}//class
And i set classpath of the oracle DB in system environment as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.
And i set path for jre in user variables as
C:\Program Files\Java\jdk1.7.0_17\bin;.;
i am not getting why my program is giving the error:
Error: this program is not recognised as internal or external command.
You probably won't have jre and jdk installed. If java -version has the same result install these.
I've set the classpath envoirenment but still get an error "Exception:com.mysql.jdbc.Driver"
Do you have any idea what might be wrong?
Here is my test code:
import java.sql.*;
public class JdbcExample1 {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql:///test", "root", "secret");
if(!con.isClosed())
System.out.println("Successfully connected to MySQL server...");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {}
}
}
}
Exception:com.mysql.jdbc.Driver
Is most probably not the full error message. I guess it's a ClassNotFoundException and you simply do not have the MySQL JDBC driver as part of your classpath.
When running your program, you need to list the driver as well
java -cp .;mysql-connector-java-5.1.7-bin.jar JdbcExample1
(This assumes JdbcExample1.class and the .jar file are in the current directory)
I've set the classpath envoirenment
Setting the CLASSPATH environment variable is not necessary anymore (actually it never has been necessary). As a matter of fact it creates more problems than it solves.
Use the above syntax to supply the path to your driver and run your program
As horse says, I'm pretty sure it's a 'ClassNotFoundException'.
To be sure add "e.printStackTrace();" in your catch-block.
Always best to get a stack trace.