Showing posts with label MySql. Show all posts
Showing posts with label MySql. Show all posts

25 February 2014

Read-Write Excel file in Java

Hi All,

Lets see you can read/write the data from/to Excel worksheet(.xls file) .  Its very useful when you provide the option to export and import the data in you web page.



package myExcel;
import java.io.File;
import java.io.FileInputStream;

import  org.apache.poi.hssf.usermodel.HSSFSheet;  
import  org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import  org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;

public class ReadExcel {
  public static void main(String[] args) {
    try
    {
      File f = new File("C:\\Users\\dsharma\\Desktop\\Excel.xls");
      FileInputStream fin = new FileInputStream(f);
      HSSFWorkbook workbook = new HSSFWorkbook(fin);
      HSSFSheet tempSheet;
      HSSFRow tempRow;
      HSSFCell tempCell;
      for (int i = 0; i < workbook.getNumberOfSheets() ; i++) {
        tempSheet = workbook.getSheetAt(i);
        System.out.println("Sheet - \""+tempSheet.getSheetName()+"\"");
        /*
         *  remember getLastRowNum() returns the 0 based index
         *  so we have to use ( "<=" )
         *  
         *  in for loop  [ j <=  tempSheet.getLastRowNum() ]
         */                 
        for (int j = 0; j <= tempSheet.getLastRowNum() ; j++) {
          tempRow = tempSheet.getRow(j);      
          if(tempRow!=null)
          {
            for (int j2 = 0; j2 <tempRow.getLastCellNum(); j2++) {
              tempCell = tempRow.getCell(j2);
              System.out.printf("%-15s|",tempCell);
            }
          }          
          System.out.println("");
        }
        System.out.println("\n\n");
      }
    }
    catch(Exception ex)
    {
      ex.printStackTrace();
    }    
  }
}

This will read you excel file specified at line number 15. and will print the data in all the sheets inside your excel workbook.

And Lets see how can you create and write excel file(.xls) from your Java Code.
package myExcel;

import java.io.File;
import java.io.FileOutputStream;

import  org.apache.poi.hssf.usermodel.HSSFSheet;  
import  org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import  org.apache.poi.hssf.usermodel.HSSFRow;

public class WriteExcel {
  public static void main(String[] args) {
    try{          
      HSSFWorkbook workbook = new HSSFWorkbook();      
      HSSFSheet tempSheet = workbook.createSheet("Created Sheet");
      
      //Create first row reference from the sheet "tempSheet"
      HSSFRow tempRow = tempSheet.createRow(0);
      
      //add the 3 column and value in first row
      tempRow.createCell(0).setCellValue("Roll No.");
      tempRow.createCell(1).setCellValue("Name");
      tempRow.createCell(2).setCellValue("Passed?");
      
      //adding 5 students details
      for (int i = 0; i < 5; i++) {
        //create second row. as first is header
        tempRow = tempSheet.createRow(i+1);
        
        //add three columns value
        tempRow.createCell(0).setCellValue(i+1);
        tempRow.createCell(1).setCellValue("Student "+(i+1));
        tempRow.createCell(2).setCellValue(i%2==1);
      }
        
      //outputstream object of the file to be created
      File f = new File("C:\\Users\\dsharma\\Desktop\\New_Excel.xls");    
      FileOutputStream fout = new FileOutputStream(f);
      workbook.write(fout);
    }
    catch(Exception ex){
      ex.printStackTrace();
    }
  }
}

You can see for both read-write we need few new reference, yes we need a library file. Called "Apache POI library",  don't worry you can download the that jar file from the below links.
Download POI

So this is the basic to read and write the Excel file in Java.  Now if you find its typical to implement it in you JSP-Servlet webproject?? get the below sample project(Eclipse Project.  jdk1.7  used).  Don't worry for the library for JSP project, I have included all the jar file inside the project.

Download Eclipse Project(.ZIP)

Happy Coding and Sharing.. :)

23 September 2013

Download - Uploading in JSP - Servlet with MySql DB

Hello Friends,

Lets see how can we code to upload and download file in JSP and Servlet.  Here I am using the database MySql.  I'm saving the file in database directly, I used the Medium Blob to store the file in database. Remember as I'm using medium blob(Max. size=16 MB) so I am considering we will upload a file with maximum size 15 MB.

By default MySql packet size is 1 MB so to support the uploading for 15 MB file, we need to change a attribute in my.ini file.

MySql installed directory > bin > "my.ini" file
search for "max_allowed_packet" you will find a line with value "1M" change to "15M"
max_allowed_packet =  1M 

max_allowed_packet = 15M
Now your MySql server is capable to transfer a big data packet to server size upto 15MB.

Create the table to store the document in MySql server
CREATE TABLE IF NOT EXISTS 'documents' (
  'Doc_id' int(11) NOT NULL AUTO_INCREMENT,
  'FileName' varchar(100) NOT NULL,
  'type' varchar(20) NOT NULL,
  'upload_time' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  'content' mediumblob NOT NULL,
  'upload_by' varchar(50) NOT NULL,
  PRIMARY KEY ('Doc_id')
)


Lets code for first index page which is used to select the file to upload..
Index.html
<form enctype="multipart/form-data" action="uploadfile.jsp" method="post" onsubmit="return verify()">      
<table border='1'>
<tr>
   <td>   
      Remember you can upload only MS-word, MS-Excel, txt and PDF files.max size = 15mb       
   </td>
</tr>
<tr>
   <td>
      <input type="file" name="filename" id="filename"
      accept=".txt,
           application/pdf,
           application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
           application/vnd.ms-excel,
           application/vnd.openxmlformats-officedocument.wordprocessingml.document,
           application/msword"/>                                                            
   </td>
</tr>
<tr>
   <td>
      <input type="submit" value="Save File" />
   </td>
</tr>
</table>
</form>
Code for uploadfile.jsp file which is used to get the select file and upload it to server.
uploadfile.jsp
<%
String rtempfile = File.createTempFile("temp","1").getParent(); 

// get the file from the previous page form           
// save the file in temporary directory of server
// specify the max size = 15MB
MultipartRequest multi = new MultipartRequest(request,rtempfile, 15*1024*1024);

Enumeration files = multi.getFileNames();

String st="insert into documents(filename, type,content, upload_by) values (?,?,?,?)";

// get the connection object from another class MyConnection's method getConnection();
// and create the prepareStatement
PreparedStatement psmt=MyConnection.getConnection().prepareStatement(st);

         
String name="";
String fileExtesion="";
File ff =null;
FileInputStream fin =null;

while (files.hasMoreElements())
{
   name=(String)files.nextElement();                                        
   ff = multi.getFile(name);
   fileExtesion = ff.getName().substring(ff.getName().lastIndexOf("."));
   
   // check user has select the correct file or not
   boolean fileAllowed = fileExtesion.equalsIgnoreCase(".txt")||
                         fileExtesion.equalsIgnoreCase(".pdf")||
                         fileExtesion.equalsIgnoreCase(".doc")||
                         fileExtesion.equalsIgnoreCase(".docx")||
                         fileExtesion.equalsIgnoreCase(".xls")||
                         fileExtesion.equalsIgnoreCase(".xlsx");
   
   if((ff!=null)&&fileAllowed)
   {
     
     try
     {
       fin=new FileInputStream(ff);
       psmt.setString(1, ff.getName());
       psmt.setString(2, fileExtesion);
       psmt.setBinaryStream(3,(InputStream)fin, (int)(ff.length()));
       psmt.setString(4, "Logged User name or ID");        // pass the user name or id 
       boolean sss = psmt.execute();
       
       out.print("uploaded successfully..");
       out.print("<br/> Go to <a href='downloadfile.jsp'>Download</a> page");
     }
     
     catch(Exception e)
     {
       out.print("Failed due to " + e);
     }
     
     finally
     {
      // next statement is must otherwise file will not be deleted from the temp as fin using f.
      // its necessary to put outside otherwise at the time of exception file will not be closed.
           fin.close();
           ff.delete();
     }
   }
   else
   {
         out.print("Please select the correct file...");
   }// end of if and else
}// end of while

MyConnection.CloseConnection();     // close the connection
%>

get the list of the uploaded file and link to download the file.
downloadfile.jsp
<table border="1">
  <tr>
    <th>File Name</th>
    <th>Uploaded By</th>
    <th>File Type</th>
    <th>Upload Time</th>
    <th>Action</th>
  </tr>
<%
  String query = "select doc_id,filename,type, upload_time, upload_by from documents";
  ResultSet rs = MyConnection.getResultFromSqlQuery(query);
  int count =0;
  while(rs.next())
  {
    out.println("<tr>"
        + "<td>"+rs.getString(2)+"</td>"
        + "<td>"+rs.getString(5)+"</td>"
        + "<td>"+rs.getString(3)+"</td>"
        + "<td>"+rs.getString(4)+"</td>"
        + "<td>"
        +   "<a href='download.jsp?Doc_id="+rs.getInt(1) +"'> Download </a>"
        + "</td>"
        + "</tr>");
    count++;
  }
  rs.close();
  MyConnection.CloseConnection();
  if(count==0)
  {
    out.println("<tr><td colspan='4'> No File Found..!! </td></tr>");
  }
%>            
</table>
This page will give you the list of the file uploaded by any user with few details and a link to download the file from server.  As file is saved in database in blob so we have to create the file from blob and have to send it to client.

Lets see the code which extract the information from database and send the file to client.
download.jsp
<%
  String doc_id = request.getParameter("Doc_id");     
  String query = "select filename, type, content from Documents where doc_id = " + doc_id;
  ResultSet rs = MyConnection.getResultFromSqlQuery(query);
  rs.next();
  
  // clear the response header information.
  response.reset();                        
  // check the file type and set the header contentType accordingly..   
  if(rs.getString(2)==".txt")
  {
      response.setContentType("application/octet-stream");
  }
  else if(rs.getString(2)==".pdf")
  {
      response.setContentType("application/pdf");
  }
  else if((rs.getString(2)==".doc")||rs.getString(2)==".docx")
  {
      response.setContentType("application/msword");
  }
  else if((rs.getString(2)==".xls")||(rs.getString(2)==".xlsx"))
  {
      response.setContentType("application/vnd.ms-excel");
  }
  // add header information to response object
  response.addHeader("Content-Disposition","attachment; filename="+rs.getString(1));
  // create the byte array from Blob
  Blob blb = rs.getBlob(3);
  byte[] bdata = blb.getBytes(1, (int) blb.length());
  
  // get the response Output stream object to write the content of the file into header
  OutputStream output =  response.getOutputStream();
  output.write(bdata);
  output.close();
  // close the obejct of ResultSet
  rs.close();
  
  // close the connection object.. 
  MyConnection.CloseConnection(); 
%>

Remember you have to create the table document as specified at top.

You need to change the MyConnection class.  Provide you database credentials.
MyConnection.java
public class MyConnection
{    
  static Connection con;
  public static Connection getConnection()
  {
    try
    {            
      if(con==null)
      {
        Class.forName("com.mysql.jdbc.Driver");  
        String url = "jdbc:mysql://localhost:3306/Your_DB_Name?"+
                     "user=db_user&password=user_password";
        con= DriverManager.getConnection(url);
      }
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }        
    return con;
  }
  
  public static void CloseConnection()
  {
    try
    {
       con.close();
       con = null;
    }
    catch (SQLException e)
    {
       e.printStackTrace();
    } 
  }
  
  public static ResultSet getResultFromSqlQuery(String SqlQueryString)
  {
     Statement stmt;
     ResultSet rs = null;
     try
     {  
        getConnection();  
        stmt = con.createStatement();
        rs = stmt.executeQuery(SqlQueryString);
     }
     catch (SQLException e)
     {
        e.printStackTrace();
     }       
     return rs;
  }
}
To make it work you also required two jar files-
1. MySql Connector jar file download
2. Another jar file to handle the uploading download
you need to add the reference of these two files into your project.

You can download the netbeans sample project. Download


Happy Coding..

10 September 2013

MySql connection string to connect with MySql database in Java


Hi Friends,

Lets see how to use the mysql connector jar file to create the connection with MySql database in Java.
As MySql is freeware sometime we think about to use the MySql with our Java application but we get failed to create the connection with MySql db.

You need to add the reference of mysql connector jar file to your project to create the connection with MySql database. You can download this connector jar file from here.

You can also download the net-beans MySql connection sample project from here. Its a zip file just extract it and Net Beans project is ready.

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mysqlconnection; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; /** * * @author DeepakSharma */ public class MySqlConnection { /** * @param args the command line arguments */ public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); /** * TODO you need to provide the db user to access db * and the password of that user */ Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/YOUR_DB?user=db_user_name&password=db_user_password"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from tableA"); while(rs.next()) { // TODO database login goes here System.out.println(rs.getInt(1) +"/"+ rs.getString(2)); } System.out.println("done"); } catch (Exception ex) { ex.printStackTrace(); } } }

Happy Coding.. :)