I am using Netbeans 16 and Java 19.0.2 on Windows 11.
I am getting:
java.lang.ClassNotFoundException: org.sqlite.JDBC
when I try to access a new sqlite file:
package com.thompco.propertymanager.table;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Database {
String filename;
Connection connection;
public Database(String filename) throws ClassNotFoundException {
this.filename = filename;
connect();
}
public final void connect() throws ClassNotFoundException {
try {
Class.forName("org.sqlite.JDBC");
String url = String.format("jdbc:sqlite:%s", filename);
connection = DriverManager.getConnection(url);
System.out.println("Connection to SQLite has been established.");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
public static void main(String[] args) {
try {
Database database = new Database("newFile.sqlite");
database.connect();
database.createTransactionTable();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I (think) I have added the sqlite jar to my path:
I tried to add it at the top of my file:
It looks like you added the sqlite jar to the list of jars for the library Absolute Layout.
Now you still need to make sure that this library is added to your project (a prerequisite before you can import the classes in your source code).
Hints:
You likely should have added sqlite as a separate library.
It would be more advisable to use the Maven build system and specify dependencies in pom.xml. That one can be version controlled. And Maven will download the libraries on your behalf.
Related
I'm testing sonar in order to ensure the closing database connections and I'm having extrange results I don't understand.
I'm trying two versions of the code executing the maven goal "sonar:sonar" from eclipse with the embeded maven version 3.3.9.
I've tried with three versions of sonarqube server: 5.6.6, 6.2 and 6.4.
With this code
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class TestClosingResources {
public static void main(String[] args) {
Connection con = null;
ResultSet rsGet = null;
PreparedStatement psGet = null;
try {
DriverManager.registerDriver (new com.mysql.jdbc.Driver());
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "test", "test");
psGet = con.prepareStatement("SELECT * FROM TEST");
rsGet = psGet.executeQuery();
int counter = 0;
while (rsGet.next()) {
counter++;
System.err.println(counter);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rsGet != null) {
rsGet.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
rsGet = null;
try {
if (psGet != null) {
psGet.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
psGet = null;
}
}
}
I have these issues about closing resources:
sonarqube 5.6.6:
Close this "Connection"
Close this "PreparedStatement"
sonarqube 6.2:
Close this "Connection"
Close this "PreparedStatement"
sonarqube 6.4:
Close this "Connection"
My question with this code is:
Why does 5.6.6 and 6.2 complain about PreparedStatement when it's
closed exactly the same than the ResultSet?
And whith this code (only changes the way I retrieve the connection, it doesn't matter if it would work or not)
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class TestClosingResources {
public static void main(String[] args) {
Connection con = null;
ResultSet rsGet = null;
PreparedStatement psGet = null;
try {
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/testci");
con = ds.getConnection();
psGet = con.prepareStatement("SELECT * FROM TEST");
rsGet = psGet.executeQuery();
int counter = 0;
while (rsGet.next()) {
counter++;
System.err.println(counter);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rsGet != null) {
rsGet.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
rsGet = null;
try {
if (psGet != null) {
psGet.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
psGet = null;
}
}
}
sonarqube 5.6.6:
Close this "PreparedStatement"
sonarqube 6.2:
Close this "PreparedStatement"
sonarqube 6.4:
no issues about closing resources
My questions with this code are:
Why does 5.6.6 and 6.2 complain about PreparedStatement when it's
closed exactly the same than the ResultSet?
Why doesn't any version complain about not closing the connection?
Thanks
The reason why some issues are not detected in more recent versions is due to the fact that static analyzer doing the analysis was improved.
Plugin used for Java source code analysis is called SonarJava, and it has independent release cycle than SonarQube. You should always use the latest release to obtain best results. Use update center on your SonarQube server to update to the latest available release.
I'm trying to do a small application that take some data from a db by connecting to a remote DB2 server using following example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionExample
{
public static void main(String[] args) {
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://localhost:50000/exampledb";
String user="db2inst1";
String password="password";
Connection connection = null;
try {
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(connection!=null){
System.out.println("Connected successfully.");
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
I get this error:
com.ibm.db2.jcc.am.SqlException: [jcc][10389][12245][3.67.27] Errore nel caricamento della libreria nativa db2jcct2, java.lang.UnsatisfiedLinkError: no db2jcct2 in java.library.path: ERRORCODE=-4472, SQLSTATE=null
further infromation here:
http://www.justexample.com/wp/connect-db2-java/
http://www-01.ibm.com/support/docview.wss?uid=swg21419978
I don't understand where to find missing library, on the JDBC library downloaded from the IBM site is missing, have I to copy it from the remote DB2 server or I have to point to the remote location?
thanks in advance best regards.
I found specific package inside IBM embedded software
I suppose you know how to add a jar file in the library of the app. The driver that you are looking for can be found in the IBM folder that generates when you install DB2.
For the driver go to C:/Program Files/IBM/SQLIB/Java there you can find the db2jcc.
First I make one R_D1.jrxml file in iReport 5.1.0.
My Java code to execute the report looks like:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
public class DbReportFill{
Connection con;
public void generateReport() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sentiment","root", "abcd");
System.out.println("Filling report...");
JasperFillManager.fillReportToFile("/home/abcd/report/R_D1.jrxml",new HashMap<String, Object> (), con);
System.out.println("Done!");
con.close();
} catch (JRException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new DbReportFill().generateReport();
}
}
When I execute the class I get the following exception:
Filling report...
net.sf.jasperreports.engine.JRException: Error loading object from file : /home/abcd/report/R_D1.jrxml
at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:127)
at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:99)
at net.sf.jasperreports.engine.JasperFillManager.fillToFile(JasperFillManager.java:117)
at net.sf.jasperreports.engine.JasperFillManager.fillReportToFile(JasperFillManager.java:666)
at DbReportFill.generateReport(DbReportFill.java:24)
at DbReportFill.main(DbReportFill.java:56)
Caused by: java.io.StreamCorruptedException: invalid stream header: 3C3F786D
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:802)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at net.sf.jasperreports.engine.util.ContextClassLoaderObjectInputStream.<init>(ContextClassLoaderObjectInputStream.java:58)
at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:122)
... 5 more
I am not sure what I am doing wrong, or what this exception means.
Your main problem here is that you have not compiled the file. Think of the JRXML file as a Java source file. To run your java file you have to compile it first, and then you can run. The jrxml file is simply the human readable XML file that describes what you want to happen.
To compile the file you do:
JasperCompileManager.compileReport("/home/abcd/report/R_D1.jrxml");
This is going to return you and instance of a JasperReport, which is the compiled file. (this is often written out to a .jasper file, so you do not have to compile the report on each run, but that is beyond the scope of this question). Once you have this you can then fill the report.
Also, unrelated, but worth mentioning, is that you should be closing the you database connection in a finally block. As in your current example it is never closed, since an exception is thrown. A finally block will ensure that even in the event of an exception it would be closed.
You sample method should look like:
public void generateReport() {
Connection con
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sentiment","root", "abcd");
System.out.println("Compiling report...");
JasperReport jasperReport = JasperCompileManager.compileReport("/home/abcd/report/R_D1.jrxml");
System.out.println("Filling report...");
JasperFillManager.fillReportToFile(jasperReport,new HashMap<String, Object> (), con);
System.out.println("Done!");
} catch (JRException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null){
con.close();
}
}
}
Hope that helps. Good luck.
If you are creating ".jrxml file" by using ireport tool then which will give you .jasper file ...If you don't want to compile then you can use already compiled .jasper file in your java program like this:
JasperCompileManager.compileReport("/home/abcd/report/R_D1.jasper");
Thanks,
Krish
Does anyone know what the best way is to create a new oracle database connection. This is what I currently have:
private static getConnection() throws Exception {
if (!isDriverRegistered){
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
isDriverRegistered = true;
}
return DrvierManager.getConnection(connectionString);
}
You are not supposed to register the driver yourself; the JDBC driver itself will do that, when its class is loaded. So, do not call DriverManager.registerDriver yourself.
There are two steps: make sure the JDBC driver class is loaded, and get a connection.
To load the JDBC driver class, use a line like this:
Class.forName("oracle.jdbc.OracleDriver");
Then get the connection with a call to DriverManager.getConnection:
Connection conn = DriverManager.getConnection(connectionString);
Note that if you are using a newer JDBC version and a suitable driver, you do not even need to load the driver class explicitly; it will be found and loaded automatically (via Java's service discovery mechanism). In that case you only need to call DriverManager.getConnection.
this class may help you
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCHelper {
public static void close(Statement obj)
{
try
{
if(obj!=null)
obj.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet obj)
{
try
{
if(obj!=null)
obj.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public static void close(Connection obj)
{
try
{
if(obj!=null)
obj.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public static Connection getConnection()
{
Connection con = null;
String url = "url" //give url
String pwd = "password";//give password
String uid = "userId";//give userid
try
{
Class.forName("oracle.jdbc.OracleDriver"); //pass driver name
con = DriverManager.getConnection(url,uid,pwd);
con.setAutoCommit(false);
}
catch(Exception e)
{
if(con!=null)
try {
con.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
return con;
}
}
i am trying to install JDBC but i dont know how, when you only have the jar file, i copied it to my java ext folder but it keep giving me an error, can anyone show me how to complete install the driver and use it?
below is the codes that i used
import java.sql.*;
public class Test1
{
public static void main (String[] args)
{
String url = "jdbc:mysql://localhost:3306/sabayafr_sabmah";
String username = "root";
String password = "ma";
Connection connection = null;
try {
System.out.println("Connecting database...");
connection = DriverManager.getConnection(url, username, password);
System.out.println("Database connected!");
} catch (SQLException e) {
System.err.println("Cannot connect the database!");
e.printStackTrace();
} finally {
System.out.println("Closing the connection.");
if (connection != null) {
try {
connection.close();
} catch (SQLException ignore) {
}
}
}
}
}
And below is the Response that i get
Cannot connect to database server
Update # 3
C:\Users\AlAsad\Desktop>java -cp .;mysql-connector-java-5.0.8-bin.jar Test1
Connecting database...
Cannot connect the database!
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/
sabayafr_sabmah
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Test1.main(Test1.java:12)
Closing the connection.
You're trying to connect MySQL with the URL of a jTDS JDBC driver which is designed specifically for Microsoft SQL Server. This ain't ever going to work. Even not when you fix the current problem by placing the JAR file in classpath.
You really need the MySQL JDBC driver. Also see this answer for a short but complete tutorial
On the other hand, if you are using an IDE such as Netbeans or Eclipse you can add the jar file as a resource to the project.
You certainly have JDBC problems, but the exception isn't telling you that. Read it again:
Exception in thread "main" java.lang.NoClassDefFoundError: Test1
Caused by: java.lang.ClassNotFoundException: Test1
It's your Test1.class that it can't find, not the JDBC driver.
You should not be copying anything into the jre/lib/ext directory. That's for library extensions, not JDBC JARs. It wasn't meant as a crutch for people who don't understand how CLASSPATH works.
I'd write it more like the following. Those close methods will come in handy.
When I run it on my machine, adding the MySQL JDBC JAR to my CLASSPATH, I get the following result:
C:\java -classpath .\mysql-connector-java-5.1.6-bin.jar; persistence.utils.DatabaseUtils
product: MySQL
version: 5.1.24-rc-community
major : 5
minor : 1
Here is the source code:
package persistence.utils;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseUtils
{
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/contacts";
public static final String USERNAME = "contacts";
public static final String PASSWORD = "contacts";
public static void main(String[] args)
{
Connection connection = null;
try
{
String driver = ((args.length > 0) ? args[0] : DRIVER);
String url = ((args.length > 1) ? args[1] : URL);
String username = ((args.length > 2) ? args[2] : USERNAME);
String password = ((args.length > 3) ? args[3] : PASSWORD);
connection = getConnection(driver, url, username, password);
DatabaseMetaData metaData = connection.getMetaData();
System.out.println("product: " + metaData.getDatabaseProductName());
System.out.println("version: " + metaData.getDatabaseProductVersion());
System.out.println("major : " + metaData.getDatabaseMajorVersion());
System.out.println("minor : " + metaData.getDatabaseMinorVersion());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
close(connection);
}
}
public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
{
Connection connection = null;
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
return connection;
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement statement)
{
try
{
if (statement != null)
{
statement.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet resultSet)
{
try
{
if (resultSet != null)
{
resultSet.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void rollback(Connection connection)
{
try
{
if (connection != null)
{
connection.rollback();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
'I am trying to install JDBC'
You don't have to install JDBC. It is part of the JDK & JRE.
Try putting your .jar file in the classpath.
The library that contains the Driver (net.sourceforge.jtds.jdbc.Driver) needs to be on the classpath.
Assuming you start your application with
java Test1
then simply do
java -cp .;driver.jar Test1
where 'driver.jar' should be exchanged with the filename (relative or full path) of your database driver lib.
EDIT
A classpath tutorial will exceed the comments section below this question. Please take a cup of coffee and look at this page. It will most likely help you to continue.