How to preview jasper report using java? - java

i have created a report for my inventory control using IReport.then i found a code
to preview my report,this is that code,
package Report;
import com.mysql.jdbc.Connection;
import java.awt.Container;
import java.sql.Statement;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.swing.JRViewer;
/**
*
* #author Hasindu
*/
public class ReportView extends JFrame
{
public ReportView(String fileName)
{
this(fileName, null);
}
public ReportView(String fileName, HashMap para)
{
super("ABC Solutions Employee/Project Management System (Report Viewer)");
try {
DB dba=new DB();
Connection con=DB.getConnection();
try
{
JasperPrint print = JasperFillManager.fillReport(fileName, para,con);
JRViewer viewer = new JRViewer(print);
Container c = getContentPane();
c.add(viewer);
}
catch (JRException j){
j.printStackTrace();
}
setBounds(10, 10, 900, 700);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
} catch (Exception ex) {
Logger.getLogger(ReportView.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
but my database connection code is returning a statement,this is my database connection code,
package Report;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
public class DB {
public static Statement getConnection()throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/report", "root", "123");
Statement st=con.createStatement();
return st;
}
}
Now i have two problems,
how to edit the report preview code to connect with my database connection code
i tested report preview code by creating this database connection code,
public static Connection getCon()throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/report", "root", "123");
}
but when i run this code it's appears a empty window,
please give a support

if i understand your question correctly ,you are returning a Statement but it require Connection .don't create a statement create a connection to your db and return that connection like following code example.
in reportview class
DB dba=new DB();
Connection con=DB.getCon();
db.class
package Report;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
public class DB {
public static Connection getCon() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/report", "root", "123");
return con;
}
}

Related

Error when creating link between java and mysql

I created the connection between java and mysql as follows:
package conexao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionFactory {
public Connection getConnection() {
try {
return DriverManager.getConnection("jdbc:mysql://localhost/projetojava","xxxxxxxxxx","xxxxxxxx");
}
catch(SQLException excecao) {
throw new RuntimeException(excecao);
}
}
}
to test the connection I used this code:
package conexao;
import java.sql.Connection;
import java.sql.SQLException;
public class TestaConexao {
public static void main(String[] args) throws SQLException {
Connection connection = new ConnectionFactory().getConnection();
System.out.println("Conexão aberta!");
connection.close();
}
}
But I always get this error:
In-place deployment at \192.168.1.70\Server\html\Pouco Comum\build\web GlassFish Server 4.1.1, deploy, null, false
\\192.168.1.70\Server\html\Pouco Comum\nbproject\build-impl.xml:1048: The module has not been deployed.
See the server log for details. BUILD FAILED (total time: 0 seconds)
How can I solve?
MySQL port seems to be missing in JDBC connection URL. The default port is 3306.
Try below code:
return DriverManager.getConnection("jdbc:mysql://localhost:3306/projetojava","xxxxxxxxxx","xxxxxxxx");

Unable to connect hive2 via JDBC java program

enter image description here
As I have import all required JAR file as shown in above image.
But still it gives me error while trying to connect hive2 via java program.
Error gives me on this line.
Connection connect = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "", "");
Error:
18/05/30 17:12:15 INFO jdbc.Utils: Supplied authorities: localhost:10000
18/05/30 17:12:15 INFO jdbc.Utils: Resolved authority: localhost:10000
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.hadoop.hive.common.auth.HiveAuthUtils.getSocketTransport(Ljava/lang/String;II)Lorg/apache/thrift/transport/TTransport;
at org.apache.hive.jdbc.HiveConnection.createUnderlyingTransport(HiveConnection.java:519)
at org.apache.hive.jdbc.HiveConnection.createBinaryTransport(HiveConnection.java:539)
at org.apache.hive.jdbc.HiveConnection.openTransport(HiveConnection.java:309)
at org.apache.hive.jdbc.HiveConnection.<init>(HiveConnection.java:196)
at org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:107)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at Hive_java.main(Hive_java.java:15)
JAVA Code:
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class Hive_java{
private static String driver = "org.apache.hive.jdbc.HiveDriver"; //driver used for hiveserver2
public static void main(String[] args) throws SQLException {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
Connection connect = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "", ""); //connecting to default database
Statement state = connect.createStatement();
System.out.println("!!!!!!!!!!Running 1st query!!!!!!!!!!");
System.out.println("Listing tables in hive");
ResultSet show_tables = state.executeQuery("show tables");
while (show_tables.next()) {
System.out.println(show_tables.getString(1));
}
System.out.println("!!!!!!!!!!Running 2nd query!!!!!!!!!!");
System.out.println("Describing slave3_tbl table");
ResultSet describe_table = state.executeQuery("describe slave3_tbl");
while (describe_table.next()) {
System.out.println(describe_table.getString(1) + "\t" + describe_table.getString(2));
}
}
}

JUnit 5 - JDBC statements testing

I've begun learning unit tests. I'm working with JUnit 5 and I'd like to test my method that inserts some data into my database (using JDBC). Here's my code:
Datasource.java
import java.sql.*;
public class Datasource {
public static final String CONNECTION = "jdbc:mysql://127.0.0.1:3306/java";
private Connection connection;
public boolean open() {
try {
connection = DriverManager.getConnection(CONNECTION, "root", "");
return true;
} catch (SQLException e) {
System.out.println(e.getMessage());
return false;
}
}
public boolean insertTable() {
try {
String query = "INSERT INTO artists(name) VALUES(?)";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, "Test");
int result = stmt.executeUpdate();
if (result == 1) return true;
return false;
} catch (SQLException e) {
System.out.println(e.getMessage());
return false;
}
}
}
DatasourceTest.java
import static org.junit.jupiter.api.Assertions.*;
class DatasourceTest {
private Datasource datasource;
#org.junit.jupiter.api.BeforeEach
void setUp() {
datasource = new Datasource();
if (!datasource.open()) {
System.exit(-1);
}
}
#org.junit.jupiter.api.Test
void insertTable() {
assertTrue(datasource.insertTable());
}
}
It works fine but it actually inserts a record into my database, but I what I want to do is to simulate it. Is it possible to achieve that using only JUnit? If not, what do I need? And a simple implementation would be highly appreciated.
EDIT
I found out about a tool called Mockito, is it what I need? If so, could anyone show me how to deploy a simple test of my method insertTable()?
This is what I did using mockito to test insetTable method
import static org.junit.Assert.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
#RunWith(MockitoJUnitRunner.class)
public class DatasourceTest {
#InjectMocks
Datasource datasource;
#Mock
Connection connection;
#Mock
PreparedStatement stmt;
#Before
public void setUp() throws SQLException {
when(connection.prepareStatement(eq("INSERT INTO artists(name) VALUES(?)"))).thenReturn(stmt);
when(stmt.executeUpdate()).thenReturn(1);
}
#Test
public void testInsertTable() {
assertTrue(datasource.insertTable());
}
}
You can use the DbUnit framework with an H2 or HSQL Memory Database.
You will open real connections to a memory Database and you could check that the records is saved by using DataSets
So If using PowerMockito with version 1.6.5 I would test your code as following
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Datasource.class, DriverManager.class, Connection.class })
public class DatasourceTest {
#Mock
Connection con;
#Mock
PreparedStatement ps;
#Test
public void insertTableTest() throws Exception {
PowerMockito.mockStatic(DriverManager.class);
PowerMockito.when(DriverManager.getConnection(
Mockito.eq("jdbc:mysql://127.0.0.1:3306/java"),
Mockito.eq("root"),
Mockito.eq(""))).thenReturn(con);
Datasource ds = Mockito.mock(Datasource.class);
PowerMockito.doCallRealMethod().when(ds).open();
PowerMockito.doCallRealMethod().when(ds).insertTable();
boolean result = ds.open();
Assert.assertTrue(result);
Mockito.when(con.prepareStatement(Mockito.eq("INSERT INTO artists(name) VALUES(?)"))).thenReturn(ps);
Mockito.when(ps.executeUpdate()).thenReturn(1);
result = ds.insertTable();
Assert.assertTrue(result);
Mockito.verify(ps).setString(Mockito.eq(1), Mockito.eq("Test"));
Mockito.verify(ps).executeUpdate();
Mockito.verify(con).prepareStatement(Mockito.eq("INSERT INTO artists(name) VALUES(?)"));
}
}
Hope this helps.

JDBC connecting MySQL script need help using ScriptRunner

I have a Java application and i need it to connect with my MySQL database's SQL script using JDBC.
Here is my Java application:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package basic;
import basic.ScriptRunner;
import javax.swing.*;
import java.sql.*;
import java.io.*;
/**
*
* #author User
*/
public class javaconnect {
Connection conn = null;
public static Connection ConnectDb(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/new","login","pass");
/*As we are creating a connection on a local computer we will write the url as jdbc:mysql://localhost:3306 */
ScriptRunner runner = new ScriptRunner(conn, false, false);
runner.runScript(new BufferedReader(new FileReader("D://Java Lenti/EkonomiSoftware/src/basic/new.sql")));
return conn ;
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
return null;}
}
}
The problem is that the Java application connects through MySQL Server, not through the SQL Script. I think the problem is at Connection parameters I gave. Can anyone guide me how to change the connection to make it connect to the SQL script not to the server?
It worked for me:
package com.spring.sample.controller;
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
public class Main {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager
.getConnection(
"",
"", "");
ScriptRunner runner = new ScriptRunner(conn, false, false);
runner.runScript(new BufferedReader(new FileReader("new.sql")));
} catch (Exception e) {
e.printStackTrace();
}
}
}
new.sql
insert into hello(name) values ('test');
May be there're some mistakes at your sql file.

How to handle Jersey web services returning VO.?

Hello I am trying to implement restful web service using jersey. In which I want to set up connection to a remote database and do some DML operation. Here I am attaching my code. Please help me to create the client for it. I don't know how should I handle this VO at any client. I want to use this connection object to perform DML. DbConnectioVO is the simple VO containing only one variable Connection and it's getters and setters. Thanks in advanced. sorry for bad English. Please ask me fo rany further information if needed.
import java.sql.Connection;
import java.sql.SQLException;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.java.vo.DbConnectionVO;
import oracle.jdbc.pool.OracleDataSource;
#Path("/db")
public class DbConnection {
#Path("/conn")
#PUT
#Produces(MediaType.APPLICATION_JSON)
#Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
public DbConnectionVO dbConnect(DbConnectionVO dbVO) throws Exception{
try {
Connection conn=null;
String serverName = "12.36.25.21";
String protocol="tcp";
String sid="12";
int portNo=1111;
String userName="user";
String password="pwd";
OracleDataSource dataSource = null;
Class.forName("oracle.jdbc.OracleDriver");
dataSource = new OracleDataSource();
dataSource.setDriverType("thin"); // type of driver
dataSource.setServerName(serverName); // database server name
dataSource.setNetworkProtocol(protocol); // network protocol
dataSource.setDatabaseName(sid); // Oracle SID
dataSource.setPortNumber(portNo); // listener port number
dataSource.setUser(userName); // username
dataSource.setPassword(password); // password
conn = dataSource.getConnection();
conn.setAutoCommit(false);
dbVO.setConnection(conn);
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw e;
}
return dbVO;
}
}

Categories

Resources