📜  如何使用Servlet和JDBC将映像添加到MySql数据库

📅  最后修改于: 2021-08-27 04:02:23             🧑  作者: Mango

结构化查询语言或SQL是一种标准的数据库语言,用于从关系数据库(如MySQL,Oracle,SQL Server,PostGre等)创建,维护和检索数据。在本文中,我们将了解如何向MYSQL数据库使用servlet。

MYSQL是一个关系数据库。关系数据库意味着数据以关系(表)的形式存储和检索。 Servlet是支持Java的Web服务器或应用服务器上运行的Java程序。它们用于处理从Web服务器获取的请求,处理请求,生成响应,然后将响应发送回Web服务器。 Servlet的属性是它们在服务器端工作。而且它们能够处理从Web服务器获得的复杂请求。在本文中,Eclipse IDE用于执行servlet,MYSQL工作台用于运行MYSQL数据库。可以按照以下步骤使用servlet和JDBC将映像添加到MYSQL数据库中:

  1. 步骤1:打开Eclipse IDE,然后在右上角找到2个图标。悬停时,它将显示Java EE和Java。由于我们将处理一个Web项目,因此我们将选择Java EE。选择它后,转到File-> New-> Dynamic Web Project

  2. 步骤2:现在,我们需要将MySQL的JDBC驱动程序(连接器– JAR_FILE)复制并粘贴到WebContent文件夹中存在的WEB-INF文件夹的lib文件夹中。 (该项目的所有外部库都需要在这里)。

  3. 步骤3:现在,我们需要创建一个主页,该主页将显示一个表单,用户可以在其中上传图像文件。我们可以在WebContent文件夹中创建JSP以及HTML文件。对于实例,我们将创建AddFile.jsp 。我们还需要更新web.xml文件,以更新其“欢迎文件列表”。我们必须在“欢迎文件”列表中添加AddFile.jsp。
    
        AddFile.jsp
    
    
  4. 步骤4:现在,我们需要为上面创建的AddFile.jsp添加代码。该文件的代码如下:
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    
    
    
    
    Add File Here
    
    
       
         
         
                       
         
                        
         
                        
              
           
  5. 步骤5:现在,我们将创建一个类,该类将用于使用JDBC与MySql数据库建立连接,并且以后可以随时使用该连接来反映数据库上的任何内容。例如,我们将创建“ MyConnection。 Java的“类”和“ getConnection()”静态方法来获取连接,如下所示:
    import java.sql.*;
      
    public class MyConnection {
      
        public static Connection 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(
                    new com.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 machine 
                      and "3306" is the port number 
                      and "FileUploadDatabase" is the name 
                      of the database.
      
                   2. UserName: "root", which is set 
                      while creating a database server in
                      MySql Workbench.
                   3. Password: "root"   
                */
      
                return con;
            }
            catch (SQLException e) {
      
                System.out.println(e.getMessage());
            }
            return null;
        }
    }
    
  6. 步骤6:现在,我们将创建一个数据库和“用户”表,该表将存储从HTML表单传递来的内容。查询相同,如下所示:
  7. 步骤7:现在,我们将创建一个Servlet,它将接收来自网页的请求并执行所有业务逻辑,并将内容存储在MySql数据库中。对于实例,我们将其命名为“ serv。 Java”。以下是此servlet中的代码:
    // Java program to implement
    // the servlet
    package controllers;
      
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
      
    import javax.servlet
        .ServletConfig;
    import javax.servlet
        .ServletException;
    import javax.servlet
        .annotation.MultipartConfig;
    import javax.servlet
        .annotation.WebServlet;
    import javax.servlet
        .http.HttpServlet;
    import javax.servlet
        .http.HttpServletRequest;
    import javax.servlet
        .http.HttpServletResponse;
    import javax.servlet.http.Part;
      
    import Dao.UploadFileDao;
    import connection.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)
      
    public class serv extends HttpServlet {
      
        // auto generated
        private static final long serialVersionUID = 1L;
      
        public serv()
        {
            super();
        }
      
        // This Method takes in All the information
        // required and is used to store in the
        // MySql Database.
        public int uploadFile(String firstName,
                              String lastName,
                              InputStream file)
        {
            String SQL
                = "INSERT INTO users "
                  + "(first_name, last_name, "
                  + "photo) values (?, ?, ?)";
            int row = 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 column
                    preparedStatement.setBlob(3, file);
                }
      
                // Sends the statement to
                // the database server
                row = preparedStatement
                          .executeUpdate();
            }
            catch (SQLException e) {
                System.out.println(e.getMessage());
            }
      
            return row;
        }
      
        // As Submit button is hit from
        // the Web Page, request is made
        // to this Servlet and
        // doPost method is invoked.
        protected void doPost(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException
        {
      
            // Getting the parametes from web page
            String firstName
                = request.getParameter("firstName");
      
            String lastName
                = request.getParameter("lastName");
      
            // Input stream of the upload file
            InputStream inputStream = null;
      
            String message = null;
      
            // Obtains the upload file
            // part in this multipart request
            Part filePart
                = request.getPart("photo");
      
            if (filePart != null) {
      
                // Prints out some information
                // for debugging
                System.out.println(
                    filePart.getName());
                System.out.println(
                    filePart.getSize());
                System.out.println(
                    filePart.getContentType());
      
                // Obtains input stream of the upload file
                inputStream
                    = filePart.getInputStream();
            }
      
            // Sends the statement to the
            // database server
            int row
                = UploadFileDao
                      .uploadFile(firstName,
                                  lastName,
                                  inputStream);
            if (row > 0) {
                message
                    = "File uploaded and "
                      + "saved into database";
            }
            System.out.println(message);
        }
    }
    

    注意:上面的代码不能在在线IDE上运行。

输出:

  • 我们可以在运行代码后查看数据库,方法是单击“在编辑器中打开值”来检查上传到数据库中的图像,如下所示:

  • 单击“在编辑器中打开值”后,将弹出一个窗口,显示以三种格式存储在数据库中的图像:二进制格式,文本格式和图像格式。

  • 现在,如果我们单击图像选项,我们将能够看到上传的图像。