JDBC connection works in IDE (eclipse), but not in .jar file - java

I'm really looking at a mystery here. I created a Java program in Eclipse and established a JDBC connection. The code is the following:
import java.sql.*;
public class Login {
public static void main(String[] args) {
try {
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager
.getConnection("jdbc:sqlserver://localhost;databaseName=testdb; integratedSecurity=true;");
//adding port 1433 doesn't make a difference
System.out.println("Connection successful");
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("select * from testtable");
while (rs.next()) {
line = rs.getString(2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
When I'm running it within eclipse, everything's fine. The database and tables are good, library and authentication in the Java Built Path are set and I get the result I want, namely "Hello World", which is a string in the selected table.
But creating an executable JAR file and running it throws the exception "This driver is not configured for integrated authentication". It does not even connect, so even if there was an error in the database it wouldn't matter at this point.
Even more confusing is the fact, that some weeks earlier, I also created an executable JAR file and it worked!
OS: Windows Vista Home Premium x86
JDBC driver location: "C:\sqljdbc_4.0\enu\sqljdbc4.jar"
Native library location: "C:\sqljdbc_4.0\enu\auth\x86"
Java version: Java 7 Update 17 and JDK 7 Update 17
Previousely, I used Update 21, but I changed back to check if the driver could be the reason.
So, any suggestions? I'd be very grateful!

Check the runtime classpath of eclipse, then try to create a system level "CLASSPATH" variable and add the same path. Once the variable is set, execute it in new command prompt or reload the environment variables
Make sure your executable jar has the dependency in MANIFEST.MF for all the necessary jars (along with MainClass)
Finally, It is always a practice in Java to make the first alphabet in Capital ("Login" instead of "login")

Actual problem is that if you run your project from eclipse, it will automatically add run arguments that are defined in run/run config//arguments, so you run your program with properly set path to sqljdbc_auth.dll. But if you export your application to .jar file and just run it, you will get these errors cause there is no correct classpath to auth file.
So, if you run your app from command line with proper arguments, it should be working.

Related

SQLException even after loading JDBC driver correctly

I'm new to java and I am using Visual Studio Code for making a Java project. I'm trying to write SQL queries after loading driver in Visual Studio Code, but I'm repeatedly getting SQLException. Here is my project folder:
src
-com/folder
-db
-DBConnection.java
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(path, username, password);
} catch (ClassNotFoundException | SQLException ex) {
ex.printStackTrace();
return false;
}
Every time I run, I get the following error
Exception in thread "main" java.sql.SQLException: No suitable driver
found for jdbc:mysql:localhost:3306/assign
I'm getting correct results when I run the same program in the src folder.
The most common reason for this type of error is missing updated jar in classpath folder.
If you are using latest version of jdbc jar make sure it correctly points to classpath where the jar is located.
Hint: put some debug statement before invoking of class so that you can be sure correct jar is invoking everytime.

Can't connect to MySQL database: No suitable driver found

I'm having some troubles with java and jdbc.
In particular, while my code perfectly works in a NetBeans project, when i try to execute it on a terminal or on my ubuntu vps (which is where i need it to work) i always get this exception:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/quakes
First thing first: yes, i'm adding the jdbc .jar to the execute command and the compile command; Yes, i've even tried to add
Class.forName("com.mysql.jdbc.Driver");,
but I always get a ClassNotFoundException: com.mysql.jdbc.Driver exception
The .jar i'm using is the exact same that i use in the NetBeans project, so i know i have the right thing, and even downloading it again from the official site won't change a thing.
Yes, the database exists, and the result doesn't change if i try to connect to another db.
I also tried switching to postgresql (yes, i didn't forget to change the url), but to no avail, it still can't find the driver.
With this, i'm guessing that the actual error is in the compile/execute commands, but even them should be ok:
javac *.java <-cp mysql-connector-java-5.1.41-bin.jar > (the <> parenthesis means that i tried compiling with and without specifying the classpath);
java TAW -cp mysql-connector-java-5.1.41-bin.jar,
In case you want to see it, here's the method that tries to connect to the database:
public Connection getConnection() throws SQLException {
if (conn == null) {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+
this.dbname,this.user,this.pass);
}
return conn;
}
Does anyone have any idea on why this happens?
You need to put the classpath option for java before the name of your main class, otherwise it is regarded as program arguments:
java -cp mysql-connector-java-5.1.41-bin.jar;. TAW
You can use this method step by step to create connetion.
it is an example connectivity:
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection("jdbc:mysql://localhost/feedback?"
+ "user=sqluser&password=sqluserpw");

How do I connect to a local SQLite in Java without this ClassNotFoundException?

I'm trying to set up a simple Java application to connect to a SQLite database but keep receiving:
ClassNotFoundException: org.sqlite.jdbc.
I've downloaded the sqlite jdbc driver jar and placed it in the same directory as the .java, and I'm compiling on the command line with:
javac -cp sqlite-jdbc-3.7.2.jar sqlite3test.java
At runtime I then get the above exception. Below is the code:
import java.sql.*;
public class sqlite3test
{
public static void main(String args[])
{
Connection c = null;
try
{
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:cs261.db");
}
catch ( Exception e )
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully");
}
}
How do I fix this issue?
Thanks.
Check the database version installed, in my case it was: SQLite version 3.8.2
I am using sqlite-jdbc-3.8.9.1.jar which is the greater version number than of the database installed and it is working perfectly.
You have to make sure the jar file version should be greater than or equal to the database version installed in your system.
From the latest version of java (from Java 6+) you don't need to load your class file.
Remove the following line and try it should work.
Class.forName("org.sqlite.JDBC");
Note: I suggest you to rename your class name from sqlite3test to Sqlite3Test though its not mandatory. According to the JAVA code convention class name should always start with Caps letter.
There are different ways to load the driver into your classpath:
place the jar into the $JAVA_HOME/jre/lib/ext folder
using maven dependencies
using java -cp
if you are using the IDE like eclipse then right click the project -> build path -> configure build path -> libraries -> add external jars and locate your jar there.
For your reference : http://www.sqlitetutorial.net/sqlite-java/sqlite-jdbc-driver/

error: package com.sap.conn.jco does not exist on ubuntu

I already install jco3 for linux.
I'm using ubuntu 16.04 x86_64 and java-8-oracle
as the documentation said, i need to add LD_LIBRARY_PATH and CLASSPATH to jco directory.
export LD_LIBRARY_PATH=/home/zain/sapjco
export CLASSPATH=/home/zain/sapjco/sapjco3.jar
then create simple jco connection test
import com.sap.conn.jco.*;
public class testjco {
public static void main(String[] args) {
JCO.Client mConnection;
try {
mConnection = JCO.createClient("301", // SAP client
"somecoolguy", // userid
"****", // password
"EN", // language
"XXX", // application server host name
"00"); // system number
mConnection.connect();
System.out.println(mConnection.getAttributes());
mConnection.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
}
but when i run my project i got error
error: package com.sap.conn.jco does not exist
is there any particular step i missed?
I don't know if you've already done this but:
export LD_LIBRARY_PATH=/home/zain/sapjco
export CLASSPATH=/home/zain/sapjco/sapjco3.jar
only work in the current bash instance, which means that if you ever close that terminal window then that export path will be gone. One way to keep it is to add it to your ~/.profile
then you can just run this source ~/.bashrc in order to refresh your bash window.
Don't know if that helped since I have never coded Java in Ubuntu, only on Mac with Eclipse/Idea. Anyways, if that's not how to do it, then there's a problem with the way you imported your sapjco3.jar to your project.
You also need to use your CLASSPATH environment variable and pass it as classpath argument to your JVM instance that shall run your project.
But I don't think that you are really at the step of running your project, you must be already failing to compile your class testjco. (By the way, I recommend to follow the common Java naming conventions and let all class names start with an uppercase letter.)
You are importing the package com.sap.conn.jco which belongs to the SAP Java Connector 3.0 (sapjco3.jar), but in your code you use the JCo API from package com.sap.mw.jco of the outdated SAP Java Connector 2.0/2.1 (sapjco.jar). That does not work and cannot be compiled.

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

Categories