Share & learn

Through Innovative Digital Library

How to store pdf file in mysql database?

Write a code to store pdf file in mysql database in Java.
 



Answers

Posted by Paul on April 25th 2018 13:26 PM

Here a pdf file will be inserted into the mysql database. PDF file is stored in database in 'blob' format. A BLOB (binary large object) is a varying-length binary string that can be up to 2,147,483,647 characters long. Steps : 1. Create database connection. 2. Create object of File class to open file. 3. Using instance of PreparedStatement class insert file in form of pdf in database. Table structure :

CREATE TABLE IMAGE
(

id varchar(10),
IMG BLOB

);

Posted by Paul on April 25th 2018 13:28 PM

Here is the code :

// Java program to store pdf file to mysql database
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.io.File;
import java.io.*;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.*;

public class 
PDFToDB {
    
    
Connection connection;
    
Statement statement;
    
ResultSet rs;
    
PreparedStatement pst;
    
Blob blob;
    
InputStream in;
    
InputStream input;
    
OutputStream output;

    
PDFToDB() {
        
        
// database connectivity
        
try {
            
            Class.
forName("com.mysql.jdbc.Driver");
            
connection DriverManager.getConnection("jdbc:mysql:///file_db""root""root");
        
        } catch (
ClassNotFoundException cnf) {
            
cnf.printStackTrace();
        } catch (
java.sql.SQLException sql) {
            
sql.printStackTrace();
        }
        
    }

    public 
void insertFile() {
        
        
File file;
        try {
        
            
// pdf file to be uploaded
            
file = new File("D:\\Tyger.pdf");

            
int fileLength = (int) file.length();
            
InputStream stream = (InputStream) new FileInputStream(file);
            
            
// db query to insert file in database 
            
pst connection.prepareStatement("insert into image (img) values(?)");
            
pst.setAsciiStream(1streamfileLength);

            
pst.executeUpdate();
        } catch (
Exception e) {
            
e.printStackTrace();
        }
    }


    public static 
void main(String args[]) {
        
PDFToDB obj = new PDFToDB();
        
obj.insertFile();
        
System.out.println("File inserted to database successfully!!!");
        
    }
}
Answer Question

Your email address will not be published. Required fields are marked *

  • Minimum 20 character
MBMC

related questions

Most liked questions

Most answered questions

Login
MBMC Refresh
Register
MBMC Refresh
Forgot password
Ask a Question
Minimum 20 character
Minimum 20 character
Reply
Minimum 20 character
MBMC Refresh