Structured Query Language or SQL is a standard Database language which is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, SQL Server, PostGre, etc. In this article, we will understand how to add an image to the MYSQL database using servlet.
MYSQL is a relational database. Relational database means the data is stored as well as retrieved in the form of relations (tables). Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send the response back to the webserver. The properties of the servlets are that they work on the server-side. And they are capable of handling complex requests obtained from the webserver. In this article, the Eclipse IDE is used to execute the servlet and MYSQL workbench is used to run the MYSQL database. The following steps can be followed to add an image into the MYSQL database using servlet and JDBC:
- Step 1: Open Eclipse IDE and on the top right corner You’ll find 2 icons. Upon hovering, it will show JAVA EE and JAVA. As we will be working with a web project, so we will choose JAVA EE. After selecting it, go to File -> New -> Dynamic Web Project.
- Step 2: Now We need to copy and paste the JDBC Driver for MySQL (Connector – JAR_FILE) in lib folder of WEB-INF folder which is present in WebContent folder. (All the external libraries for the project needs to be here).
- Step 3: Now, we need to create a home page which will present a form wherein a user can upload an image file. We can create a JSP as well as HTML file in the WebContent folder. For Instance, we will create AddFile.jsp. We need to update the web.xml file as well, to update its Welcome File List. We have to add AddFile.jsp in the Welcome File List.
<welcome-file-list><welcome-file>AddFile.jsp</welcome-file></welcome-file-list>chevron_rightfilter_none - Step 4: Now, we need to add the code for the AddFile.jsp which has been created above. The code for this file is as follows:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%><!DOCTYPE html><html><head><metacharset="ISO-8859-1"><title>Add File Here</title></head><body><formmethod="post"action="serv"enctype="multipart/form-data"><div><label>First Name:</label><inputtype="text"name="firstName"size="50"/></div><div><label>Last Name:</label><inputtype="text"name="lastName"size="50"/></div><div><label>Profile Photo: </label><inputtype="file"name="photo"size="50"/></div><inputtype="submit"value="Save"></form></body></html>chevron_rightfilter_none - Step 5: Now, we will make a class which will be used to establish the connection with MySql database using JDBC and can use that connection anytime in future to reflect anything upon Database. For instance, we will create “MyConnection.java” class and “getConnection()” static method to get a connection as follows:
importjava.sql.*;publicclassMyConnection {publicstaticConnection getConnection(){// As java.sql package classes// contains Checked Exceptions,// we have to surround it with// Try/Catch Block.try{// We have to register the// Driver class present in// com.mysql.jdbc package.DriverManager.registerDriver(newcom.mysql.jdbc.Driver());// To get the connection,// 3 params need to be passed in// DriverManager.getConnection() method.Connection con= DriverManager.getConnection("jdbc:mysql:// localhost:3306/"+"FileUploadDatabase","root","root");/* 1. URL: "jdbc:mysql://", is the address"localhost: " is the local machineand "3306" is the port numberand "FileUploadDatabase" is the nameof the database.2. UserName: "root", which is setwhile creating a database server inMySql Workbench.3. Password: "root"*/returncon;}catch(SQLException e) {System.out.println(e.getMessage());}returnnull;}}chevron_rightfilter_none - Step 6: Now, we will create a database and table “users” which will store the contents passed from the HTML Form. The query for the same is as follows:
CREATE DATABASE FileUploadDatabase
CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
first_name varchar(45) DEFAULT NULL,
last_name varchar(45) DEFAULT NULL,
photo mediumblob,
PRIMARY KEY (`id`)
) - Step 7: Now, we will create a Servlet which will take the request from the webpage and perform all the business logic and store the contents in MySql Database. For Instance, we will name it as “serv.java”. The following is the code in this servlet:
// Java program to implement// the servletpackagecontrollers;importjava.io.IOException;importjava.io.InputStream;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.SQLException;importjavax.servlet.ServletConfig;importjavax.servlet.ServletException;importjavax.servlet.annotation.MultipartConfig;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.Part;importDao.UploadFileDao;importconnection.copy.MyConnection;// This is the annotation-based// mapping URL to Servlet.@WebServlet("/serv")// This annotation defines the maximum// file size which can be taken.@MultipartConfig(maxFileSize =16177215)publicclassservextendsHttpServlet {// auto generatedprivatestaticfinallongserialVersionUID = 1L;publicserv(){super();}// This Method takes in All the information// required and is used to store in the// MySql Database.publicintuploadFile(String firstName,String lastName,InputStream file){String SQL="INSERT INTO users "+"(first_name, last_name, "+"photo) values (?, ?, ?)";introw =0;Connection connection= MyConnection.getConnection();PreparedStatement preparedStatement;try{preparedStatement= connection.prepareStatement(sql);preparedStatement.setString(1, firstName);preparedStatement.setString(2, lastName);if(file !=null) {// Fetches the input stream// of the upload file for// the blob columnpreparedStatement.setBlob(3, file);}// Sends the statement to// the database serverrow = preparedStatement.executeUpdate();}catch(SQLException e) {System.out.println(e.getMessage());}returnrow;}// As Submit button is hit from// the Web Page, request is made// to this Servlet and// doPost method is invoked.protectedvoiddoPost(HttpServletRequest request,HttpServletResponse response)throwsServletException, IOException{// Getting the parametes from web pageString firstName= request.getParameter("firstName");String lastName= request.getParameter("lastName");// Input stream of the upload fileInputStream inputStream =null;String message =null;// Obtains the upload file// part in this multipart requestPart filePart= request.getPart("photo");if(filePart !=null) {// Prints out some information// for debuggingSystem.out.println(filePart.getName());System.out.println(filePart.getSize());System.out.println(filePart.getContentType());// Obtains input stream of the upload fileinputStream= filePart.getInputStream();}// Sends the statement to the// database serverintrow= UploadFileDao.uploadFile(firstName,lastName,inputStream);if(row >0) {message="File uploaded and "+"saved into database";}System.out.println(message);}}chevron_rightfilter_noneNote: The above code cannot be run on the online IDE.
Output:
- We can view the database after running the code to check the images uploaded in the database by clicking on “Open Value In Editor” as follows:
- After we click on “Open Value in Editor”, a window will pop up showing the image which is stored in the database in three formats: Binary Format, Text Format and Image format.
- Now, if we click on the image option, we will be able to see the image which is uploaded.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Java Servlet and JDBC Example | Insert data in MySQL
- MySQL | Database Files
- Database Backup from MySQL
- PHP | MySQL Database Introduction
- PHP | MySQL ( Creating Database )
- PHP | Inserting into MySQL database
- MySQL | DATABASE() and CURRENT_USER() Functions
- JDBC Drivers
- Introduction to JDBC
- MySQL | Common MySQL Queries
- Difference between Database Administrator (DBA) and Database Engineer
- How to pre populate database in Android using SQLite Database
- Difference between Centralized Database and Distributed Database
- Difference between ODBC and JDBC
- Difference between JDBC and Hibernate in Java
- Establishing JDBC Connection in Java
- Image Processing in Java | Set 6 (Colored image to Sepia image conversion)
- Image Processing in Java | Set 4 (Colored image to Negative image conversion)
- Image Processing in Java | Set 3 (Colored image to greyscale image conversion)
- JDBC Using Model Object and Singleton Class
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

