eSp
eSp

Reputation: 45

JavaServlet handling SQL errors

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class QueryServlet extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException, ServletException
    {
        PrintWriter out=res.getWriter();
        res.setContentType("text/html");

        Connection conn = null;

        final String id = UUID.randomUUID().toString();

        Map m = req.getParameterMap();
        Set s = m.entrySet();
        Iterator it = s.iterator();

        try {
            conn = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/orders", "username", "password");

             String sqlStr = "insert into transactions (LogID,KeyName,KeyValue) "
             + "values (?,?,?)";

             while(it.hasNext()){

                 Map.Entry<String,String[]> entry = (Map.Entry<String,String[]>)it.next();

                 String key             = entry.getKey();
                 String[] value         = entry.getValue();

                 try (PreparedStatement stmt = conn.prepareStatement(sqlStr)) {
                 stmt.setString(1, id);
                 stmt.setString(2, key);
                 stmt.setString(3, value[0].toString());

                 out.println("<html><head><title>Callback Script</title></head><body>");
                 out.println("<h3>Inserted into the database:</h3>");
                 out.println("<p>Parameter: " + key + " and Value = " + value[0].toString() + "</p>");        
                 int updateCount = stmt.executeUpdate();
                 for (Enumeration<String> en = req.getParameterNames(); en.hasMoreElements();) {
                    String paramName = en.nextElement();
                    String paramValue = req.getParameter(paramName);
                    }
                 }
             }
           } catch (SQLException ex) {
              ex.printStackTrace();
           } finally {
                out.close();
            try {
                if (conn != null) conn.close();
            } catch (SQLException ex) {
               ex.printStackTrace();
               }
        }
    }          
}

If some error happens with the MySQL Database like wrong credentials, any SQL syntax error at all should be handled and displayed but it is not displaying at all.

Any advice on this or am I coding it wrong?

Cheers

Upvotes: 0

Views: 140

Answers (1)

developerwjk
developerwjk

Reputation: 8659

What you have will only print to the logs. To print to the page, use out.print

catch (SQLException ex) 
{
   ex.printStackTrace(); //print to log
   out.print("<br/>Error: " + ex.getMessage()); //print to page
}

On credentials errors you won't want to print the actual message to the page, as it might include the credentials. So you should isolate the part the opens the connection with its own try-catch, which can be nested inside this one.

try
{
   conn = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/orders", "username", "password");
}
catch(Exception ex_connError)
{
    out.print("<br/>Error making db connection");
}

Upvotes: 1

Related Questions