I'm just trying to connect to postgres (13.0.1) from java (11.0.8) on Debian 10 and get the error below:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class cli_test {
public static void main(String[] args) {
try {
Connection connection = null;
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/myproj", "postgres", "<pwd>");
System.out.println("Connection established successfully");
} catch (Exception e) {
System.out.print("error: \n" + e.toString() + "\n" + e.getMessage());
}
}
}
I run these commands:
CLASSPATH=/usr/lib/jvm/java-11-openjdk-amd64/lib/postgresql-42.2.18.jar
javac -verbose cli_test.java
java cli_test
I have verified that the jar file exists in that location and is set to 755 permissions.
I get this error:
java.lang.ClassNotFoundException: org.postgresql.Driver
I have spent hours searching online and found many others with this problem. No other solutions I found have fixed it. I'm trying to do this without a java ide, just a text editor.
That's not a Java problem but you use bash in a wrong way. Setting CLASSPATH=.. will not make this environment variable available to java in the program call afterwards. Try
export CLASSPATH=.:/usr/lib/jvm/java-11-openjdk-amd64/lib/postgresql-42.2.18.jar
javac -verbose cli_test.java
java cli_test
or
CLASSPATH=.:/usr/lib/jvm/java-11-openjdk-amd64/lib/postgresql-42.2.18.jar java cli_test
Related
I am trying to connect a little Java App to a SQL Server database using Visual Studio Code. This is my code:
import java.sql.*;
public class App {
public static void main(String[] args) {
String connectionUrl =
"jdbc:sqlserver://DESKTOP-03898L2DB;"
+ "Database=DB_PA;"
+ "User=checkou-GN;"
+ "Password=sapassword;"
+ "IntegratedSecurity=true;"
+ "encrypt=true;trustServerCertificate=true";
;
try {
//String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
//Class.forName(driver);
try (Connection conn = DriverManager.getConnection(connectionUrl);) {
System.out.println("Connected");
}
} catch (SQLException e) {
System.out.println(e);
e.printStackTrace();
}
}
}
But when I run it I get this message:
cd "c:\Users\checki\Desktop\JAVA\pruebaN3\prueba\src\" && javac App.java && java App
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://DESKTOP-033L2DB;Database=DB_PA;User=checkou-GN;Password=sapassword;IntegratedSecurity=true;encrypt=true;trustServerCertificate=true
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:252)
at App.main(App.java:16)
I've succesfully imported the connectors and the SDK as shown in the picture:
The thing is that I've tried to do the same on another computer and it seems to work fine:
The main difference for me is the command that the shell is executing: in the first case is using javac and java and in the working case is using:
& 'C:\Program Files\Java\jdk-18\bin\java.exe' '--enable-preview' '-XX:+ShowCodeDetailsInExceptionMessages' '#C:\Users\sempr\AppData\Local\Temp\cp_9hxr1t8qo8sc8hiaiyq1qpyf9.argfile' 'App'
I don't know what the problem could be and I've tried almost everything. In Eclipse and Intelij the program works fine on both machines but with VSCode in the first machine does not work.
You are using Code Runner for the first case? Please choose Run Java button instead of Run Code button. The Code Runner will not find the referenced libraries.
my name is Omar
i am following the instructions in this webpage https://www.tutorialspoint.com/sqlite/sqlite_java.htm in order to compile a sample program of java conected with sqlite3.
sample program
import java.sql.*;
public class SQLiteJDBC {
public static void main( String args[] ) {
Connection c = null;
try {
// Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Opened database successfully");
}
}
i downloaded the sqlite connector sqlite-jdbc-3.7.2.jar but according to the webpage above, i Added the address of downloaded jar file sqlite-jdbc-(VERSION).jar in my class path(the same class path of mysql address connector) and place the sqlite-jdbc-3.7.2.jar in C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext just like mysql connector driver.
but i got bad results when i try to run it in command line
"No suitable driver found for jdbc: sqlite: test.db"
i run java -classpath ".;sqlite-jdbc-3.7.2.jar" SQLiteJDBC with the sqlite-jdbc-3.7.2.jar in the same folder in command line but i got bad results too.
"No suitable driver found for jdbc: sqlite: test.db"
Where sqlite-jdbc-3.7.2.jar connector should be placed according to connect java and sqlite just as myql do?
anyhelp is appreciated
thank you in advance
Omar
You should download and use the newest SQLite driver 3.27.2.1 from this site: https://bitbucket.org/xerial/sqlite-jdbc/downloads/
I tried it with 3.7.2 and got the same error. But with 3.27.2.1 it works well.
Essential parts of the Code:
(Taken from example from Book: Java How to Program 10th ed, By: Paul Deitel, Harvey Deitel (p. 1063)):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DisplayAuthors
{
public static void main(String args[])
{
final String DATABASE_URL = "jdbc:derby:books";
try (
Connection connection =
DriverManager.getConnection(DATABASE_URL, "user", "pass");
)
{
// ...
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
}
}
}
I'm on Ubuntu 16.04
Although Java website for Java DB says the db is included in JDK, I have
learned after few hours of web searches that openJDK java, the recommended
install on Ubuntu, does not come with the java db.
The website that had that helpful information suggested to run:
sudo apt-get install sun-javadb-client sun-javadb-core
Which produced error and did not install.
So I downloaded jdk-8u111-linux-x64.tar.gz, extracted as instructed, and just to be safe(I believe, I could have just set JAVA_HOME, DERBY_HOME to extracted location, and which did "half-worked" upto ij parts[see below]), removed everything from my /usr/lib/jvm/java-8-openjdk-amd64/ and replaced with the content of what I downloaded.
And added these in my .bashrc:
JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/
DERBY_HOME=/usr/lib/jvm/java-8-openjdk-amd64/db
export DERBY_HOME
Entered in terminal to create database and insert data as instructed in book:
$JAVA_HOME/db/bin/ij
connect 'jdbc:derby:books;create=true;user=usr;password=pass';
run 'book-basic-table-create-and-insertions.sql';
exit;
It produces a file books with db info+/data inside it.
At ./ there's also a file named derby.log that contains these informations:
----------------------------------------------------------------
Wed Dec 14 19:01:58 EST 2016:
Booting Derby version The Apache Software Foundation - Apache Derby - 10.11.1.2 - (1629631): instance a816c00e-0158-ffc9-1471-000006d047c8
on database directory /tmp/deleteme-IuI/books with class loader sun.misc.Launcher$AppClassLoader#6f94fa3e
Loaded from file:/usr/lib/jvm/java-8-openjdk-amd64/db/lib/derby.jar
java.vendor=Oracle Corporation
java.runtime.version=1.8.0_111-b14
user.dir=/tmp/deleteme-IuI
os.name=Linux
os.arch=amd64
os.version=4.4.0-53-generic
derby.system.home=null
Database Class Loader started - derby.database.classpath=''
----------------------------------------------------------------
Wed Dec 14 19:04:25 EST 2016: Shutting down Derby engine
----------------------------------------------------------------
Wed Dec 14 19:04:27 EST 2016:
Shutting down instance a816c00e-0158-ffc9-1471-000006d047c8 on database directory /tmp/deleteme-IuI/books with class loader sun.misc.Launcher$AppClassLoader#6f94fa3e
----------------------------------------------------------------
Compiled and ran:
javac DisplayAuthors.java # compiles without error
java DisplayAuthors
Program outputs:
java.sql.SQLException: No suitable driver found for jdbc:derby:books
at java.sql.DriverManager.getConnection(DriverManagerager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.javaava:247)
at DisplayAuthors.main(DisplayAuthors.java:15)
How do I get the program to work?
You are missing the load driver section of code
e.g.
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
...
try {
Class.forName(driver);
} catch(java.lang.ClassNotFoundException e) {
...
}
see http://docs.oracle.com/javadb/10.8.3.0/getstart/rwwdactivity3.html for an example
Edit
As a proof I have done the following
create simple java project in Eclipse
add derby.jar, derbynet.jar & derbyclient.jat to classpath
My Code
public static void main(String[] args) {
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
try {
Class.forName(driver);
} catch(java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
final String DATABASE_URL = "jdbc:derby:myDB;create=true;user=user;password=pass";
try (
Connection connection = DriverManager.getConnection(DATABASE_URL, "user", "pass");
)
{
// ...
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
}
}
This runs without Exceptions
I'm having difficulties in Java with an SQLITE database provided in a separate JAR file.
Surprisingly, the sqlite database seems to be accessed even after removing the JAR file, exiting and restarting the program and even after rebooting the machine.
I'm using the Xerial driver sqlite-jdbc-3.7.2.jar (for org.sqlite.JDBC).
EDIT: very same issue with sqlite-jdbc-3.8.6.jar.
Xerial JDBC driver is published here:
https://bitbucket.org/xerial/sqlite-jdbc
I'm really puzzled. Is there some kind of persistent cache for this particular JDBC driver? or is it something I missed regarding JDBC in general?
CODE SAMPLE:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqliteJDBCTest {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite::resource:jar:file:doesntexistJAR.jar!/doesntexistDB.sqlite");
System.out.println("connection = " + connection);
statement = connection.createStatement();
System.out.println("statement = " + statement);
rs = statement.executeQuery(" SELECT * FROM nonexistentTable WHERE key = 'nonexistentKey'");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
The above code sample shows the first step of the problem: on the first run, DriverManager.getConnection(..) throwed an exception as expected:
$ java -jar sqliteJDBCTest.jar
java.sql.SQLException: failed to load jar:file:doesntexistJAR.jar!/doesntexistDB.sqlite: java.io.FileNotFoundException: doesntexistJAR.jar (Aucun fichier ou dossier de ce type)
at org.sqlite.Conn.open(Conn.java:92)
at org.sqlite.Conn.<init>(Conn.java:57)
at org.sqlite.JDBC.createConnection(JDBC.java:77)
at org.sqlite.JDBC.connect(JDBC.java:64)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at SqliteJDBCTest.main(SqliteJDBCTest.java:18)
But, since then, for each run I get the following output:
>java -jar sqliteJDBCTest.jar
connection = org.sqlite.Conn#3fee733d
statement = org.sqlite.Stmt#5acf9800
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such table: nonexistentTable)
at org.sqlite.DB.newSQLException(DB.java:383)
at org.sqlite.DB.newSQLException(DB.java:387)
at org.sqlite.DB.throwex(DB.java:374)
at org.sqlite.NativeDB.prepare(Native Method)
at org.sqlite.DB.prepare(DB.java:123)
at org.sqlite.Stmt.executeQuery(Stmt.java:121)
at SqliteJDBCTest.main(SqliteJDBCTest.java:23)
In this example, the SQLException "SQL error or missing database" is not the error we're expecting!
Not only is the database missing, but even the JAR file supposed to contain it!
So how come getConnection() doesn't throw an exception in the first place?
Short answer: because of a bug in the Xerial JDBC driver.
When one requests the Xerial driver a connection by calling DriverManager.getConnection(jdbc:sqlite::resource:jar:file:<local_location_of_JAR>!/<name_of_database_file>), the driver creates a copy of the database file on the temporary directory specified by the Java system property java.io.tmpdir and then operates on this copy.
The problem is that when the original JAR is removed, the driver loads the copy the next time(s) one uses the same getConnection() call. For me, this is a bug; the driver should at least check that the (possibly remote) JAR file pointed to by the URL is still there...
Second problem (the one described in the CODE SAMPLE of this post): when the original JAR file doesn't exist, a "copy" of the (non-existent) database is created, and the next time(s) getConnection() is called with the same parameters, the driver directly returns a phantom connection to this empty database that was never found...
I submitted this story in a bug report on the Xerial JIRA website:
https://bitbucket.org/xerial/sqlite-jdbc/issue/158/drivermanagergetconnection-not-returning
I'm trying to connect to a DB2 database using JDBC. Therefore I downloaded the DB2 driver db2jcc.jar and added the path to the classpath while compiling and running my application (I'm not using an IDE).
The following is the source of my Test-Application:
import java.sql.*;
public class TestApp {
public static void main(String[] args){
try {
Class.forName("com.ibm.db2.jcc.DB2Driver");
}
catch (Exception e) {
System.out.println(e);
}
}
}
Does anybody know, where my problem is?
Try compiling:
'javac -cp ".;(path)/db2jcc.jar;(path)/db2jcc_license_cu.jar" TestApp.java'
Then running
'java -cp ".;(path)/db2jcc.jar;(path)/db2jcc_license_cu.jar" TestApp'
You only need quotes if spaces in the file/path names also.