Showing posts with label MYSQL. Show all posts
Showing posts with label MYSQL. Show all posts

Parametrized IReport in Your Java Project ?

This is a very important post I've to make during this series about IReports which is to enlighten somebody who reads this to add Parametrized IReport into the Java Project.

The whole post in steps which will surely be comforting to most of the readers, so that it'll be easy to follow this.

1. First, Step is to finalize your IReport. Hope You've got your IReport Application Opened. Then, click on the Parameter You've defined on the Report Inspector. 





 2. Go to Properties window at the right bottom of your application window.








3. Make sure, you tick off 'Use as a prompt'. Compile the IReport & Close IReport Application.

4. Then, open up your Java Project Create a Package as repObj (any name) .



5. Store your IReport files & import *.jasper & image files relating to your IReport in to the package.






6. Create another package 'report' & make a java class as ReportView & copy the following code inside it.


package report;

import DBConnect.Connect;
import java.awt.Container;
import java.sql.Connection;
import java.util.HashMap;
import javax.swing.*;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.swing.JRViewer;

public class ReportView extends JFrame
{
    public ReportView(String fileName)
    {
        this(fileName, null);
    }
    public ReportView(String fileName, HashMap para)
    {
        super("Set Your Application name in the Super Class");

        Connect dba = new Connect();
        Connection con = dba.connect();

        try
        {
            JasperPrint print = JasperFillManager.fillReport(fileName, para, con);
            JRViewer viewer = new JRViewer(print);
            Container c = getContentPane();
            c.add(viewer);            
        } 
        catch (Exception Exception)
        {
            System.out.println("ERRORS IN JASPER REPORT "+Exception);
        }
        setBounds(10, 10, 900, 700);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
    
}



7. Now, create a button in the frame to fire up your IReport & a text box to pass the parameters.

8. Go inside the Button & copy the following Code.

        HashMap para = new HashMap();
        para.put("Order_No",jtxt_Order_No.getText());
        ReportView rv = new ReportView("..\\iControl\\src\\repObj\\Order.jasper",para);
        rv.setVisible(true);




 You may need to import HashMap class & report.ReportView class( you've created) in your frame *.java file. 

As parameter of put method you've to pass IReport Parameter Name & Text Box Value. ReportView Parametrized Constructor should be given Relative *.jasper path Passed, make sure you do that.

9. Now, you've to import the IReport Libraries in to the Java Project.







Import the  IReport Libraries in the Image below. You can find them in your IReport Installation. In default they'll be "C:\Program Files\Jaspersoft\iReport-4.5.1\ireport\modules\ext".




10. Now, run your file. Type a value into the Text box & Check whether it's working. Most probably it would.


Enjoy !

Creating Parametrized IReport ?

                          This is a short post about creating a successful IReport with Parameters. The idea is called 'Parametrized IReport'. 

If you're familiar with the IReport it's alright, but if you're not then follow the previous posts I've noted down @ notesofharsha here.

Let's start creating a parametrized IReport.

1. Hope you're with IReport Application opened. Now, Go to Report Inspector in the left side of your application window & select 'Parameters'. 



2.  Right Click & Select Add Parameter. 



3. Right Click & Select Rename to rename the parameter. You can give a name in the pop up box coming out.



4. Then, you've to adjust your MYSQL query in order to get your parameter passed into the output. So to do that, right click on the Report Name in the Report Inspector & click Edit Query.




5. You've to write your MYSQL query as follows.



SELECT
     order_table.`Ord_No` AS order_table_Ord_No,
     order_table.`Qty` AS order_table_Qty,
     order_table.`Order_Date` AS order_table_Order_Date,
     order_table.`Sup_No` AS order_table_Sup_No,
     order_table.`Prod_No` AS order_table_Prod_No,
     order_table.`Invoice_Date` AS order_table_Invoice_Date
FROM
     `order_table` order_table

WHERE
     order_table.`Ord_No`=$P{Order_No}


6. You've to correctly enter the exact name of your parameter in the WHERE clause. 


7. After all, you've to test it. In order to do that, Click Preview in the tool bar right above your workspace.





8. Now, you'll be asked to enter parameters. Just Enter the correct parameters So that the Report will be shown accordingly.




9. Click 'Refresh' button to retest.


Enjoy !


Change the date format in IReport ?

                                              If you've created an IReport, you may have noticed that the default date format is kind of irritating & for sure that doesn't be the date format you expected to display on your report. You'll notice that below.



So, to change the format, follow the steps shown below.

1. Select the field you want to change format from the Report Inspector in the left corner. Right Click & Field Pattern.


2. Then, select Date in the Patterns & select a format.



3. Or just select 'Custom Format' and type Date format. You have to set the format like yyyy-MM-dd or there will be errors in the report.

4. Then, compile report and Preview.

Enjoy IReport !

 

Start Creating Report in IReport ?

                                                                    I wanted to make this post simple as much as possible. All the description is in steps so that it would be easy to anybody whose following this, going through them.

1. Launch IReport Application.

2. Press Ctrl+N or File - > New to start create a new report.




3. Then, you'll notice the 'New File' wizard. Select a Report Layout for your report & click 'Next'.



4. Then, pick a file name & location to save your work & click 'Next'.



5. You'll notice that the next window is for creating query for the IReport.


If you've got the MYSQL query you can type it in the space or click 'Design Query' to design your query.

6 . If you've created your connection successfully for available database with tables your tables will be visible so that you can drag & drop them in the space.


More MYSQL clauses can be used here but I didn't want any of those in the work that I've been doing.

7.Finish Creating Basic Report.



The rest of the important Steps will be noted down @ notesofharsha under 'IReport' Tag.


Creating a connection with IReport ?

This is one of the easiest blog post I've ever noted down @ 'notesofharsha'.

You may have already used IReport (Jasper Reporting Software) for reporting purposes of your java application.

If yes, skip this post. This is like letter 'A' for an Advanced English Learner.

If no, & if you're just getting to know IReport. This is a way to go. The very first step of IReport is creating a connection with the database. Here I use MYSQL database.

1. Launch IReport application.


 2. Click 'New Connection' icon, blow the menu bar. (Plug in to the DB Icon)





3. Then, Click button 'New' in the pop up box.


3. Select 'Database JDBC Connection'. (this applies if you're jasper reporting for your java application)


4. Way to go. Then, under JDBC URL: jdbc:mysql://localhost/(Your Database Name) set the name of your database that you're currently attempting to connect. Username is for your username, may be it's root then type root under username & password is blank in default, but you can make your own settings here and don't forget to tick save password.

Most importantly, set a name for your connection so that you can use it constantly.



5. Test the connection to check whether all the settings are in order.





If you see a pop up box appears like in the screen shot. You've already done it alright. Click 'Save' in order to proceed.

6. Tick the default tick under the connection name you set. So that you can use this connection every time you launch your application.



Then, click close & you're ready to go. Enjoy IReporting !

Basic Signup from with PHP ?

Hi!

This will be helpful if you're a newbie or desperately finding some code to copy paste during your very first site project experience with PHP.

Anyway, try to learn something out of this as it's easy to understand as well as simple to follow. As usual the guide is given in steps so that you don't need to bother reading long sentences to keep going with the guide.

Let's go.

1. First, you need to create a Directory(Windows/Linux) to save your work & you've to keep this in your server. (if you're using localhost, keep it inside htdocs directory).

2. Then, run the following MYSQL code & create table to enter data.


create database phpdb;

use phpdb;

create table test(
email varchar(100) not null,
password varchar(20) not null
);


3. Then, Create a index.php file & put the following code in it.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>This is PHP Example</title>
</head>
<body>
<form action="signup.php" method="post">
<table width="629" height="191" border="1">
  <tr>
    <td width="241">Enter Email Address </td>
    <td width="372"><input type="text" name="txt_email" /></td>
  </tr>
  <tr>
    <td>Enter Password </td>
    <td><input type="password" name="txt_password" /></td>
  </tr>
  <tr>
    <td> </td>
    <td><input type="submit" value="Submit" name="btn_submit" /></td>
  </tr>
</table>
</form>
</body>
</html>


4. Then, create redirect.php & put the following code there.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>This is PHP File</title>
</head>
<body>
<?php $red = $_REQUEST["msg"]; echo $red."<br/>"; ?>
<br/>
<a href="index.php" target="_parent">GO HOME</a>
</body>
</html>


5. Then,create signup.php file & put the follwing code.

<?php

 $con = mysql_connect("localhost","root","");
 
 if(!$con)
 {
  $msg="Can't Connect to the Database ".mysql_error();
 }
 else
 {
  $dbCon = mysql_select_db("phpDB");
  
  if(!$dbCon)
  {
   $msg = "Can't Connect to the Table ".mysql_error();
  }
  else
  {
   $email = $_POST["txt_email"];
   $pword = $_POST["txt_password"];
   
   $query = mysql_query("INSERT INTO test VALUES('$email','$pword')");
   
   if(!$query)
   {
    $msg= "Can't Insert Values to the Table".mysql_error();
   }
   else
   {
    $msg = "Successfully Added to the Table !"; 
   }
  }
 }
 
 header("Location: redirect.php?msg=".$msg);
?>

Now, File Seems like follows inside the directory.




6. Now, run Web Browser & type http://localhost/folder in the address bar.


7. There's Few notes to make. In signup.php  line 3 can be replaced with your site url, username & password. Naming text boxes in index.php like :  
<input type="text" name="txt_email" .. is important in order to get their values in signup.php.

Enjoy the Code !

MySQL database backup/restore with Java Program ?



Hi!

This article is about creating a java program to backup/restore a MySQL database. The article is in two basic parts, namely Backup  & Restore.

1. Backup - Basically, the MYSQL command to backup database looks like follows.

mysqldump -u [username] -p[password] -B [dbname] -r [MYSQL file Path]

The following Code is for the java program.


public class Main{


 public void restoreDB(String path){

    String executeCmd = "C:/xampp/mysql/bin/mysqldump -u xyz -pxxyyzz -B myDB -r " + path;

    System.out.println(executeCmd);

    Process runtimeProcess;

    try
    {
       runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd });

       int processComplete = runtimeProcess.waitFor();

       System.out.println(processComplete);

       if(processComplete == 0)
       {
          System.out.println("Backup Created Successfully !");
       }
       else
       {
          System.out.println("Couldn't Create the backup !");
       }
    }
    catch(Exception ex)
    {
       ex.printStackTrace();
    }

   }

      public static void main(String[]args){

         new Main().restoreDB("C:/File.sql");
      }

}


2. Restore - Basically, the MYSQL command to restore database looks like follows.

mysql -u [username] -p[password] [databasename]<[MYSQL file Path]


In the query,

-u [username]    - is where you should type your username to access databases.

-p[password]      - is where you should type your password to the databases.

Then, you should type the name of the database which you need to backup tables to.

mysql -u xyz -pxxyyzz myDatabase<C:/file.sql

Then,Here's a java code to test run this MYSQL command.

public class Main{


 public void restoreDB(String path){

  String executeCmd = "C:/xampp/mysql/bin/mysql -u xyz -pxxyyzz myDB <" + path;

  System.out.println(executeCmd);

  Process runtimeProcess;

  try
  {
   runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd });

   int processComplete = runtimeProcess.waitFor();

   System.out.println(processComplete);

   if(processComplete == 0)
   {
    System.out.println("Restored the Backup !");
   }
   else
   {
    System.out.println("Couldn't Restore the backup !");
   }
  }
  catch(Exception ex)
  {
   ex.printStackTrace();
  }

 }

 public static void main(String[]args){

  new Main().restoreDB("C:/File.sql");
 }

}
Ah, one more thing, You can set path to MYSQL in windows & adjust line 6 as follows.

String executeCmd = "mysql -u xyz -pxxyyzz myDB <" + path;

And, You need to have Process Class invoked to run cmd.exe & execute MYSQL command in line with Command Prompt.