Inserting into MySQL table from Eclipse with html form values- Wrong syntax error

Viewed 66

I am trying to insert values that are received from an html form. Everything seems to be working until I try and insert the values and I am receiving a wrong syntax error, but I have tried changing it to no avail. Here is my code:

The connection is being established, so I am not sure whats wrong.

import java.util.Date;
import java.util.UUID;

public abstract class Log {
    private String uuid;
    private String title;
    private String content;
    private String createTimestamp;
    
  
    
    
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
       public String getUUID() {
            return uuid;
        }

        public void setUUID(String uuid) {  
            this.uuid = uuid;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public String getCreateTimestamp() {
            return createTimestamp;
        }

        public void setCreateTimestamp(String createTimestamp) {
            this.createTimestamp=createTimestamp;
            
        }
}

    package com.algonquin.loggy.servlets;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.UUID;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.algonquin.loggy.beans.Log;
    import com.algonquin.loggy.beans.TextLog;
    import com.algonquin.loggy.dao.ApplicationDao;
    import com.algonquin.loggy.dao.DBConnection;
    
    /**
     * Servlet implementation class LogsServlet
     */
    @WebServlet("/LogsServlet" )
    public class LogsServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        /**
         * @see HttpServlet#HttpServlet()
         */
        public LogsServlet() {
            super();
        }
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
         *      response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String htmlResponse = "<html><head><link rel=\"stylesheet\" href=\"style.css\"><title>Loggy Servlet Form</title></head>"
                    + "<body><form id=\"logForm\" action=\"LogsServlet\" method=\"post\" >\n"
                    + "        <h3>Create A New Log!</h3>\n"
                    + "       \n"
                    + "        <label id=\"logTitleLabel\" for=\"title\">Title :</label>\n"
                    + "        <br>\n"
                    + "        <input type=\"text\" id=\"logTitle\" name=\"title\" maxLength=\"60\">\n"
                    + "        <br>\n"
                    
                    + "        <label id=\"logContentLabel\" for=\"content\">Content :</label>\n"
                    + "        <br>\n"
                    + "        <input type=\"text\" id=\"logContent\" name=\"content\">\n"
                    + "        <br>\n"
                    + "        <button type=\"submit\" id=\"submitLog\">Submit Log</button>\n"
                    + "        \n"
                    + "        </form></body></html>";;
            PrintWriter writer = response.getWriter();
            writer.write(htmlResponse);
        }
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        
        String title = request.getParameter("title");
        String description = request.getParameter("description");
        String content = request.getParameter("content");
        String output;
        String uuid =UUID.randomUUID().toString();
        String createTimestamp=new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
        //ArrayList<Log> logsList = new ArrayList<Log>();
        Log log= new TextLog();
        
        PrintWriter writer = response.getWriter();
        try {
            
            log.setTitle(title);
            log.setContent(content);
            log.setCreateTimestamp(createTimestamp);
            log.setUUID(uuid);
            
            //logsList.add(log);
            
            output="<html><body><h3>Log successfully created</h3></body></html>";
            writer.write(output);
            }
            catch(Exception e) {
                output="<html><body><h3>Log could not be created</h3></body></html>";
                writer.write(output);
            }
        
                
        ApplicationDao dao = new ApplicationDao();
        String indexForm = "<html><head><link rel=\"stylesheet\" href=\"style.css\"><title>Loggy Servlet Form</title></head>"
                + "<body><form id=\"logForm\" action=\"LogsServlet\" method=\"post\" >\n"
                + "        <h3>Create A New Log!</h3>\n"
                + "       \n"
                + "        <label id=\"logTitleLabel\" for=\"title\">Title :</label>\n"
                + "        <br>\n"
                + "        <input type=\"text\" id=\"logTitle\" name=\"title\" maxLength=\"60\">\n"
                + "        <br>\n"
            
                + "        <label id=\"logContentLabel\" for=\"content\">Content :</label>\n"
                + "        <br>\n"
                + "        <input type=\"text\" id=\"logContent\" name=\"content\">\n"
                + "        <br>\n"
                + "        <button type=\"submit\" id=\"submitLog\">Submit Log</button>\n"
                + "        \n"
                + "        </form></body></html>";
        
        writer.write(indexForm);
        
        String insertQuery ="INSERT INTO `logs`(`uuid`, `title`, `content`, `createTimestamp`) VALUES (?,?,?,?)";
        Connection connection =DBConnection.getConnectionToDatabase();
        
        
        java.sql.PreparedStatement statement;
        try {
            statement = connection.prepareStatement(insertQuery);
            statement.setString(1,log.getUUID());
            statement.setString(2,log.getTitle());
            statement.setString(3,log.getContent());
            statement.setString(4,log.getCreateTimestamp());
            
            statement.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class DBConnection {
    
        // Database Schema
        // CREATE DATABASE loggy DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
        // CREATE TABLE logs (uuid CHAR(40) NOT NULL PRIMARY KEY, title CHAR(128),
        // content TEXT, createTimestamp Date);
    
         private static final String dbUser = "user";
            private static final String dbPassword = "password";
            private static Connection connection = null;
            
    
            public static Connection getConnectionToDatabase() {
                
    
                try {
    
                    // load the driver class
                    Class.forName("com.mysql.jdbc.Driver");
                    System.out.println("MySQL JDBC Driver Registered!");
    
                    // get hold of the DriverManager
                    connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/loggy",dbUser,dbPassword);
                } catch (ClassNotFoundException e) {
                    System.out.println("Where is your MySQL JDBC Driver?");
                    e.printStackTrace();
    
                }
    
                catch (SQLException e) {
                    System.out.println("Connection Failed! Check output console");
                    e.printStackTrace();
    
                }
    
                if (connection != null) {
                    System.out.println("Connection made to DB!");
                }
                return connection;
                
            }
            
    
              
        }
    
    package com.algonquin.loggy.dao;
    
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.sql.Timestamp;
    import java.util.ArrayList;
    import java.util.List;
    
    import com.algonquin.loggy.beans.Log;
    import com.algonquin.loggy.beans.TextLog;
    import com.algonquin.loggy.services.ApplicationService;
    
    public class ApplicationDao implements ApplicationService {
    
    
            public List<Log> listLogs() {
                    
                Log log = null;
                List<Log> logs = new ArrayList<>();
                
                try{
                    Connection connection = DBConnection.getConnectionToDatabase();
                    
                    String sql = "select * from logs";
                    
                    Statement statement = connection.createStatement();
                    
                    ResultSet set = statement.executeQuery(sql);
                    
                    while(set.next()){
                        
                        String title = set.getString("title");
                        String content =set.getString("content");
                        String createTimestamp =set.getString("createTimestamp");
                        String uuid = set.getString("uuid");
                        
                        
                        Log log1 =new TextLog();
                        log1.setTitle(title);
                        log1.setContent(content);
                        log1.setCreateTimestamp(createTimestamp);
                        log1.setUUID(uuid);
                
                        logs.add(log1);
                        
                    }
    
                }
                catch(SQLException exception){
                    exception.printStackTrace();
                }
                return logs;
    
                }
        }

 
ERROR MESSAGE:

  MySQL JDBC Driver Registered!
Connection made to DB!
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''logs' values('25de3284-4fea-4851-9215-13c51bb333cd','Log 101','this is a tes...' at line 1
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:916)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1061)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1009)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1320)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:994)
    at com.algonquin.loggy.servlets.LogsServlet.doPost(LogsServlet.java:127)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:834)

Also, I have to display the objects in an html list that each item to be deleted, if there is any advice on that, that would be appreciated as well!

1 Answers

The syntax error is:

check the manual that corresponds to your MariaDB server version for the right syntax to use near ''logs' values

This looks like you're using single-quotes (') to delimit the table name. Single-quotes in SQL are used for string delimiters, not identifier delimiters.

This is strange, because in your code you're clearly using back-ticks:

String insertQuery ="INSERT INTO `logs`(`uuid`, `title`, `content`, `createTimestamp`) VALUES (?,?,?,?)";

I'm forced to conclude that the error is not coming from the code you showed in your question. I suggest you search for other code that may be doing the INSERT differently.

Related