Java Servlet处理SQL错误

时间:2014-05-21 13:48:56

标签: mysql servlets

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();
               }
        }
    }          
}

如果MySQL数据库出现错误凭据等错误,则应处理并显示任何SQL语法错误,但根本不显示。

对此有任何建议或我编码错了吗?

干杯

1 个答案:

答案 0 :(得分:1)

您所拥有的只会打印到日志中。要打印到页面,请使用out.print

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

在凭据错误上,您不希望将实际消息打印到页面,因为它可能包含凭据。因此,你应该隔离部件,用它自己的try-catch打开连接,它可以嵌套在这个中。

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