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
Related
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.
I have try and catch block in JAVA code
import java.io.FileOutputStream;
import java.util.zip.ZipOutputStream;
public class TryTest {
public static void main(String[] args) {
String zipPath ="D:/test";
try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPath))){
String Hello ="Hello";
System.out.println("==============>"+Hello);
}catch (Exception e) {
e.printStackTrace();
}
}
}
And my compiled class look like
/*
* Decompiled with CFR 0.145.
*/
....
try {
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(string));){
String string2 = "Hello";
System.out.println("==============>" + string2);
}
....
I wounder why another try block added in compile time.
Full Source code in
https://github.com/vikram06/java_try_catch_bug
This is explained in the JLS 14.20.3.2 Extended try-with-resources :
The meaning of an extended try-with-resources statement:
try ResourceSpecification
Block
Catchesopt
Finallyopt
is given by the following translation to a basic try-with-resources
statement (ยง14.20.3.1) nested inside a try-catch or try-finally or
try-catch-finally statement:
try {
try ResourceSpecification
Block
}
Catchesopt
Finallyopt
The effect of the translation is to put the ResourceSpecification
"inside" the try statement. This allows a catch clause of an extended
try-with-resources statement to catch an exception due to the
automatic initialization or closing of any resource.
Furthermore, all resources will have been closed (or attempted to be
closed) by the time the finally block is executed, in keeping with the
intent of the finally keyword.
When you're using try with resources (I mean try (...) {... ) then Java compiler generates additional code section to display the stacktrace from local variable of type Throwable. That's because Java compiler is decomposing try with resources statement into separate tries - one for closing the resource and another for statements inside your try.
How is it displayed after decompilation - it depends on the decompiler you use.
Author of CFR here - short answer - CFR's 'resugaring' isn't perfect ;) (though the decompiled code is entirely correct, and valid.)
If you find something like this, feel free to submit a bug/improvement.
For what it's worth - the ACTUAL bytecode bears much less of a resemblance to the input - try using cfr with the arguments
--tryresources false --decodefinally false
And you get the unsugared code, which is much closer to the actual bytecode.
public static void main(String[] args) {
String zipPath = "D:/test";
try {
ZipOutputStream zipOut;
block11 : {
zipOut = new ZipOutputStream(new FileOutputStream(zipPath));
Throwable throwable = null;
try {
String Hello2332 = "Hello";
System.out.println("==============>" + Hello2332);
if (zipOut == null) return;
if (throwable == null) break block11;
}
catch (Throwable Hello2332) {
try {
throwable = Hello2332;
throw Hello2332;
}
catch (Throwable throwable2) {
if (zipOut == null) throw throwable2;
if (throwable == null) {
zipOut.close();
throw throwable2;
}
try {
zipOut.close();
throw throwable2;
}
catch (Throwable throwable3) {
throwable.addSuppressed(throwable3);
throw throwable2;
}
}
}
try {
zipOut.close();
return;
}
catch (Throwable Hello2332) {
throwable.addSuppressed(Hello2332);
return;
}
}
zipOut.close();
return;
}
catch (Exception e) {
e.printStackTrace();
}
}
I am developing an application using Swing, so before starting up I need to know a few basics regarding working with Connection. In many tutorials, I have seen that we need to create a connection Class and get the connection within the project using getConnection().
But I have created a connectionMethod is it possible to get the connection in my entire project by creating object of the connection class and using the connection?
This is my code:
package ncl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Test {
Connection connection=null;
public void connectionMethod() {
try {
Class.forName("org.h2.Driver");
connection=DriverManager.getConnection("jdbc:h2:~/test","sa", "");
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new Test().connectionMethod();
try {
// DO STUFF HERE
} catch (Exception e) {
// TODO: handle exception
}finally {
try {
new Test().connection.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}
I want to know whether this approach is good or not.
This totally depends on the practitioner that how he/she wants to code. Ideally we should follow Design Patterns in implementation to achieve many properties like Low Coupling, High Cohesion etc.
You told that in many tutorials, they make separate class which only provides connection. It is a good practice to avoid the problem of dependency and we can allocate responsibility to the classes in more efficient way. So you should also do it by creating new class which only provides the connection.
For the mentioned code, you have made some mistakes. You have first taken an instance of Test class which has connection and you didn't assign it to any variable. So you can't use it further when you need the connection. Another mistake is that you try to close the connection by creating another instance of Test class which obviously doesn't have started connection.
So, you can make appropriate suggested changes.
ConnectionFactory.java :
This will provide the connection objects.
package ncl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionFactory {
Connection connection=null;
public void connectionMethod() {
try {
Class.forName("org.h2.Driver");
connection=DriverManager.getConnection("jdbc:h2:~/test","sa", "");
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Test.java :
Write the actual code here.
package ncl;
import java.sql.SQLException;
public class Test {
public static void main(String[] args) {
ConnectionFactory connectionObject = new ConnectionFactory();
connectionObject.connectionMethod();
try {
// DO STUFF HERE
} catch (Exception e) {
// TODO: handle exception
}finally {
try {
connectionObject.connection.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}
You can use below utility class :
public class MyConnection {
private Connection con = null;
public Connection getConnection() {
try {
if (con == null) {
Class.forName("org.h2.Driver");
con = DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
}
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
}
For getting connection you can call MyConnection().getConnection();
For example :
If you want to get connection in any class then do the following :
Connection con = new MyConnection().getConnection();
I am unable to store image into MySQL database through the jdbc code below:
package com.jlcindia.jdbcfiles;
import java.sql.*;
import java.io.*;
public class Test1 {
public static void main(String []args){
Connection con=null;
PreparedStatement ps=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/jlcstudents","root","garima");
ps=con.prepareStatement("insert into filetest (cno,file) values(1,?)");
File image=new File("C:\\html images\\MickeyMouse.jpg");
FileInputStream fis=new FileInputStream(image);
ps.setBinaryStream(2, fis);
ps.execute();
System.out.println("Record Inserted");
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
if(ps!=null)
ps.close();
if(con!=null)
con.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
Error in console is as:
Exception in thread "main" java.lang.AbstractMethodError:
com.mysql.jdbc.PreparedStatement.setBinaryStream(ILjava/io/InputStream;)V
at com.jlcindia.jdbcfiles.Test1.main(Test1.java:19)
That error so far as I am aware means that the specific method hasn't been implemented, you can try however converting the file into a byte array and storing it using
ps.setBytes(<Byte Array>)
instead if the column is set to storing BLOB data
My .jsp files are not outputting characters when I use out.println inside a try statement. For example:
out.println("testing123");
try {
connectionDB = DriverManager.getConnection(DATABASE_URL, userDB, passDB);
psDB = connectionDB.prepareStatement(sql);
rsDB = psDB.executeQuery();
out.println("hello");
while(rsDB.next()){
out.println("yay");
}
} catch (Exception errorMessage) {
}
It will output "testing123" to the page but It will not output "hello" why is this, and how do I fix this? All help is appreciated. Remember this is a .jsp page.
You seems to be eating the exception in your try/catch. It seems there is some exception happening in your try block and execution is not reaching to the statement
out.println("hello");
Try to print the stacktrace and correct the code so that execution is successful.
This works so you must have Exception in your Database code.
try{
out.println("hello there!");
}
catch(Exception e ){
e.printStackTrace();
}
I think you have error in your Database code.
try this code
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
............................
......
...
..
.
try {
connectionDB = DriverManager.getConnection(DATABASE_URL, userDB, passDB);
stmt = connectionDB.createStatement();
rs = psDB.executeQuery("SELECT * from tblpost");
while(rs.next()){
out.println(rs.getString("column_Name"));
}
} catch (Exception errorMessage) {
out.println("error");
}
if you find it hard try to watch this Database Connection and JSP Display