Some of the benefits of stored procedure programming are faster execution of sql statements and also preventing sql injection. So whenever the application logic of your application is data centric, it is better to use stored procedure.

To access mysql stored procedure in your java application, you first create the stored procedure in mysql. Below is a sample created stored procedure in mysql.

   1: DELIMITER $$

   2: DROP PROCEDURE IF EXISTS `test`.`cdinsert`$$

   3: CREATE DEFINER=`root`@`localhost` PROCEDURE `cdinsert`(cID varchar(15), tdate varchar(15),cdNo int)

   4: BEGIN

   5:  if exists(select ID from cddetail where cdID=cID) then

   6:   update cddetail set transdate=tdate,cdNum=cdNo where cdID=cID;

   7:  else

   8:   insert into cddetail(cdID,transdate,cdNum) values (cID,tdate,cNo);

   9:  end if;

  10: END$$


You then create your java application  to access the stored procedure as shown below

   1: import java.sql.*;

   2: public class storproc {


   4:     Connection conn = null;

   5:     Statement stm = null;

   6:     static final String url = "jdbc:mysql://localhost/test";

   7:     static final String user = "root";

   8:     static final String pswd = "password";


  10:     //connecting to the mysql database

  11:     public Connection getConnection() {

  12:         try {

  13:             conn = DriverManager.getConnection(url, user, pswd);

  14:         } catch (Exception ex) {

  15:             System.out.println("error occured " + ex.toString());

  16:         }

  17:         return conn;

  18:     }


  20:     public void insertNew(String line) {

  21:         try {

  22:             String input[] = line.split(",");

  23:             //calling the created storedprocedure 

  24:             //and passing the required parameters

  25:             CallableStatement cs = this.getConnection().

  26:             prepareCall("{call insertnew(?,?,?)}");


  28:             cs.setString(1, input[0]);

  29:             cs.setString(2, input[1]);

  30:             cs.setInt(3, Integer.parseInt(input[2]));

  31:             cs.execute();

  32:         } catch (Exception e) {

  33:             System.out.println("errr  " + e.toString());

  34:         } finally {

  35:             try {

  36:                 conn.close();

  37:             } catch (SQLException ex) {

  38:                 System.out.println("error occured " + ex.toString());

  39:             }

  40:         }


  42:     }

  43: }


In this post, we are to discuss how to create help for your swing application using swing components. The idea is to create text file for each help file, the content can be formatted with html, then on click of a button you display a particular file in a panel. To make the panel (help page) stay on top of other opened windows of your application we can choose to display it as a dialog.check how to show a panel as dialog.

To start with we create a class that will load a help file from a source(which you have save it in the settings of your application) by passing the file name without the extension….below is the class

   1: import;

   2: import java.util.logging.Level;

   3: import java.util.logging.Logger;

   4: import javax.swing.JOptionPane;

   5: import;//download

   6: public class helpFile {

   7:     private String helpContent = null;

   8:     public helpFile(String filename) {

   9:        try {

  10:             //loading the help file from  a location stored in your settings

  11:             File file=new File(Settings.loadProperties().getProperty("xp.helpsource") +"/"+ filename +".txt");

  12:                         if (file.exists()) {

  13:                 helpContent = FileUtils.readFileToString(file);

  14:             } else {  

  15:                 JOptionPane.showMessageDialog(null, "File Does not Exist \n" + file.getPath() + "\n" + file.toString());

  16:             }

  17:         } catch (Exception ex) {

  18:             Logger.getLogger(helpFile.class.getName()).log(Level.SEVERE, null, ex);

  19:         }

  20:     }

  21:     @Override

  22:     public String toString() {

  23:         return helpContent;

  24:     }

  25: }

Then we create a panel and name it “helpdetailPanel”. We then add a JEditorPane to the Panel and then add the constructor below to the panel class

   1: public helpdetailpanel(String text) {

   2:         initComponents();

   3:         this.editor.setContentType("text/html");

   4:         this.editor.setText(text);    

   5:     }

Then in the application,on click of a button we add the code below to show a help based on the name (help file name) we pass to the “helpfile” class. Below shows the code to show the panel with the help content

   1: //helpfile is the class to load the help file from its source

   2:    helpdetailpanel hd = new helpdetailpanel(new helpFile("customers").toString());

   3:    hd.setSize(700, 700);

   4:    popupsjdialog d = new popupsjdialog(null, hd, true);

   5:    d.setVisible(true);

In the code above, “customers” is the name of a help file with a content below.

   1: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

   2: <html>

   3: <head>

   4: " "

   5: </head>

   6: <body>

   7: <span style="" bold=""

   8:  text-decoration="" underline="">&nbsp;<span

   9:  style="font-weight: bold; text-decoration: underline;">CUSTOMER

  10: INFORMATION</span> </span>

  11: <br>

  12: <br>

  13: 1. To &nbsp;add a new Customer click on the add new button. Enter <br>

  14: &nbsp; &nbsp; &nbsp;the required information and click on

  15: Save<br>

  16: <br>

  17: 2. To Edit a Customer select it from the table view, make the changes

  18: required and click on Save<br>

  19: <br>

  20: 3. To delete a Customer, select it from the table view, and click on

  21: the delete button<br>

  22: </body>

  23: </html>

The picture below shows how the help content that is displayed at runtime on click of a help button in the Customers Panel.


Cheers  !!!!!!!!!!!


Crystal reports can be created in .Net applications with different data sources including using database tables, stored procedures, typed datasets and also without a data source.

In this article we are going through how to create a crystal report for the first time using database tables as the datasource.

1. You have to create your windows project in using VS 2005. After creating the project, right on then project name in the solution explorer, select “add” and then “add new” as shown below.


2. In the add new dialog box, select “crystal Report” and name it, and then click on the add button.


3. You will be presented with the “crystal report gallery” dialog, choose “using the report wizard” and click on ok


4.In the choose data source dialog, go to the “ Create New Connection” node and then select the “OLE DB(ADO)” sub node.


4. You will then be required to provide the database connection information. Slect the “Microsoft OLE DB provider for SQL server” and click on the next button


5. Here you provide the database logon parameters


6. After successfully connecting to the database, you then select the table (s) you want to display its content on your report


6. After selecting the table(s) you select the actual columns you want to displayimage

7. After choosing the columns you will display, you can click on next to choose the columns for grouping and then for filtering, and then finally you choose the format to display your report.


8. After you have finished designing your report, you then drag a “crystal reports viewer” onto your form.


Then create a code under the form load event to show your report on for load

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ‘create a new report document 
        ‘and load the report from its source
        ‘use Application.StartupPath to get the address of your report fro deployment issues
        Dim rpd As New ReportDocument
        Me.CrystalReportViewer1.ReportSource = rpd

    End Sub

    ‘for deployment issues make sure the database paramaters are encrypted
    ‘and saved in the mysettings class

Private Sub SetDBLogonForReport(ByVal myReportDocument As ReportDocument)
       Dim myConnectionInfo As ConnectionInfo = New   ConnectionInfo()
       myConnectionInfo.DatabaseName = "datalinkDB"
       myConnectionInfo.UserID = "sa"
       myConnectionInfo.Password = "qwerty"
       myConnectionInfo.ServerName = "localhost"
       myConnectionInfo.IntegratedSecurity = "false"
       Dim myTables As Tables = myReportDocument.Database.Tables
       For Each myTable As  CrystalDecisions.CrystalReports.Engine.Table In myTables
           Dim myTableLogonInfo As TableLogOnInfo = myTable.LogOnInfo
           myTableLogonInfo.ConnectionInfo = myConnectionInfo
   End Sub

Below is a picture when the application is run



It is a common requirement in many J2SE (client,swing) applications to present data in a tabular way and also print this tabular format as a report.

Jasper reports provides implementation that makes the task of generating reports from tabular formats simple in Swing
applications. In this demonstrations, we will be using Jasper reports 3.6.1, Netbeans 6.1 and Ireport 3.6.1.

Let start by designing our report. In generating reports from tablemodels the report fields must match the column names of the tablemodel, but sometimes it becomes impractical to use the actual column names as report fields. Jasper Reports provides a way to generate reports from TableModels without having to map the actual table columns to the report fields. We can name our
report fields COLUMN_X, where x is the column index, starting with zero. Note “COLUMN” all characters should be capitals as “column” will give you error message at run time.

Also in case you have 3 columns in your table and you define a report field “COLUMN_4” , which is for column 5, null values will be displayed for each row in the report under that field. To prevent null values from displaying in a text field you can edit the expression for that field e.g. (($F{COLUMN_4}==null)? "":$F{COLUMN_4}.toString()), which means if the if the value of $F{COLUMN_4} is null ,display nothing else display the value. To do this, right click the text field and select “edit expression”, an expression editor will pop up for you to change the expression.

Below is a picture of our report at design time


After creating our report, we go to our application (using Netbeans as the IDE), we add a JTable and a JButton to our JFrame. We the create a method which accepts  the table model to create the report, tbProducts is the name of the Jtable. Check to see how to populate a list of javabean object to a Jtable

private void generateReports(String name, Map param) {
        try {

      String source = "C:/sabonay/jasperreports/" + name + ".jrxml";
            if (new File(source).exists() == false) {
      xputils.showMessage("Please go to setting and Choose report Source");

JasperReport jasperReport = JasperCompileManager.compileReport(source);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, param, new JRTableModelDataSource(tbProducts.getModel()));

            JasperViewer.viewReport(jasperPrint, false);

        } catch (Exception e) {
            System.out.println("reports Error  " + e.toString());


Cheers !!!


If you want to insert images from the file system (e.g. C:\images folder) into jasper reports at runtime, for example changing a logo depending on user selection or simply allowing the user to browse for his or her image to be displayed  in the report then here is a simple process of doing that.

Let start with the report design using ireport. In this instance the picture will be passed to the report as a parameter.

So let’s create a parameter in our report and call it “photo”


As shown in the picture above, the data type of our parameter should be “java.lang.Object”

After this, drag the image , from the tool bar, on to your report.Right click on the image and choose “Properties” from the menu


Under the image tab of the dialog box, make sure you select “java.awt.image” for the Image Expression Class. Once this is done, you are done with the report design

Lets go to netbeans , do some coding and connect our designed report to a java application.

First we need to declare a variable of type image,

Image photo;

Also we create a method , which on click of a button, loads a picture from the file system and initializes the “photo: variable.

JFileChooser fc = new JFileChooser();

private void getPicture() {

fc.setFileFilter(new FileNameExtensionFilter("Images", "jpg", "gif", "bmp"));

if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {


ImageIcon icon = new ImageIcon(fc.getSelectedFile().getAbsolutePath());

icon = new ImageIcon(icon.getImage().getScaledInstance(350, 350, Image.SCALE_DEFAULT));

photo = icon.getImage();


After getting our picture, create an instance of the Map class and pass our “variable” as a parameter.

Map<String, Object> param = new HashMap<String, Object>();

param.put("photo", photo); //the “photo” should be the same name as the parameter name in our report

We then create a method that passes our created parameter to the report and we are done. below is the method that does the job.

private void generateReports(String name, Map param) {

try {

String source = "C:/sabonay/jasperreports/" + name + ".jrxml";

if (new File(source).exists() == false) {

xputils.showMessage("Please  report Source does not exist");



JasperReport jasperReport = JasperCompileManager.compileReport(source);

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, param, new JREmptyDataSource());

JasperViewer.viewReport(jasperPrint, false);

//the false parameter makes sure the application does not close on closing the report

} catch (Exception e) {

System.out.println("reports Error " + e.toString());


Make sure to reference the necessary jasper jar files in your application


“Wow !!!! Now Thus Intereeessssting” That was how i exclaimed when i saw these interesting features of the STRING class in java. All this while when i wanted to convert a character array to a string , i had to go through a loop. For example

String password = “” ;
char[] pass = this.txtPassword.getPassword();
for (int i = 0; i < pass.length; i++) {
password = password + pass[i];

But this char[] pass can easily be converted to string by just a line of code:

char[] pass = this.txtPassword.getPassword();
String password=new String(pass);

Also another interesting feature of the string class is that you can easily get the string value out of a byte array and vice versa with so much ease. check this.

byte[] array=”sdfdfd”.getBytes();
String string=new String(array);

These are not all, there are more interesting features, exploree!!!!

Fellows, enjoy the weekend


Have you wondered how to show a panel(form) as a dialog in java applications as done in .NET applications by using the form.showDialog() method?  For example, when a user selects “Add New” from a Customer combobox, the customer panel shows as a dialog for a new entry before the user can continue. If you have been searching for this, here is your stop.

We will be making use of one JDialog, and your FORMS(JPanels in this sense).

To implement this add a JDialog to your application. Declare a variable contentPane and add the constructor like the one specified below.

private Container contentPane = null;

public popupsjdialog(java.awt.Frame parent, JPanel panel, boolean modal) {
//super(parent, modal);
contentPane = this.getContentPane();
this.setSize(panel.getSize().width + 30, panel.getSize().width + 50);
panel.setLocation(10, 30);


Your are now done. Now to show any JPanel as a dialog add the following code to your event.

helpdetailpanel hd = new helpdetailpanel(helpContent);
hd.setSize(700, 700);
popupsjdialog d = new popupsjdialog(null, hd, true);

Helpdetailpanel is a Jpanel (form) you want to show as a dialog and the popupsjdialog is an instance of the Jdialog we created its constructot above.

Cheers !!!!!!!!!!!!!!!!!