1

现在我面临这个脚本的以下两个问题。

1)当我运行类似的命令SELECT * FROM table;时,它只返回列名。当我运行类似的命令时SELECT columnName FROM table;,它会完美地显示输出。什么可能导致此错误?

2) 当我运行INSERTorDELETE命令时,我收到反馈消息说数据库已更新,但是在检查数据库时,没有进行任何更改。任何人都可以在我的源代码中看到该子句有什么问题吗?

下面分别是我的 .java 和 .jsp 文件:

数据库Servlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;

@SuppressWarnings("serial")

public class databaseServlet extends HttpServlet {
    private Connection conn;
    private Statement statement;

    public void init(ServletConfig config) throws ServletException {
        try {
            Class.forName(config.getInitParameter("databaseDriver"));
            conn = DriverManager.getConnection(
                    config.getInitParameter("databaseName"),
                    config.getInitParameter("username"),
                    config.getInitParameter("password"));
            statement = conn.createStatement();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ArrayList<String[]> out = new ArrayList<String[]>();
        ArrayList<String> columns = new ArrayList<String>();

        String query = request.getParameter("query");

        if (query.toString().toLowerCase().contains("select")) {
            //SELECT Queries
            try {
                ResultSet resultSet = statement.executeQuery(query.toString());
                ResultSetMetaData metaData = resultSet.getMetaData();
                int numberOfColumns = metaData.getColumnCount();
                for(int i = 1; i<= numberOfColumns; i++){
                    columns.add(metaData.getColumnName(i));
                }

                while (resultSet.next()){
                    String[] row = new String[numberOfColumns];
                    for (int i = 0; i < numberOfColumns; i++){
                        row[i] = (String) resultSet.getObject(i+1);
                    }
                    out.add(row);
                 }
            }
            catch (Exception f) {
                f.printStackTrace();
            }
        }
        else if (query.toString().toLowerCase().contains("delete") || query.toString().toLowerCase().contains("insert")) {
            //DELETE and INSERT commands
            try {
                conn.prepareStatement(query.toString()).executeUpdate(query.toString());
                columns.add("\t\t Database has been updated!");
            }
            catch (Exception l){
                l.printStackTrace();
            }
        }
        else {
            //Not a valid response
            columns.add("\t\t Not a valid command or query!");
        }
        request.setAttribute("query", query);
        request.setAttribute("resultSize",  out.size());
        request.setAttribute("queryResults", out);
        request.setAttribute("queryColumns", columns);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/dbServlet.jsp");
        dispatcher.forward(request,  response);
    }
}

dbServlet.jsp

<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- dbServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<%@ page import="java.util.ArrayList" %>
<head>
    <title>MySQL Servlet</title>
    <style type="text/css">
        table{border: 1px solid #FFF;}
        td{border: 1px dashed #FFF; padding: 3px; background-color: #5A5F64;}
        body{background-color: #182229; text-align: center; color: #FFF;}
        h1{font-family:"Arial", sans-serif, Helvetica;}
    </style>
</head>
<body>
    <h1>MySQL Servlet User-Interface</h1>
    <div style="width:500px; margin-right:auto; margin-left: auto; background-color:#131B21; padding: 20px;">
        <h3>Enter an SQL Command!</h3>
        <form action = "/database/database" method = "post">
        <p>
            <textarea name = "query" cols="28" rows="5"></textarea>
        </p>
        <p>
            <input type = "submit" value = "Run MySQL Servlet" />
            <input type = "reset" value = "Clear Command" />
        </p>
        </form>
        <hr>
        <TABLE id="results" align="center">
            <%
                ArrayList<String> columns = (ArrayList<String>)request.getAttribute("queryColumns");
                ArrayList<String[]> results = (ArrayList<String[]>)request.getAttribute("queryResults"); 
                out.println("<TR align='left'>");
                if(columns != null && !columns.isEmpty()){
                    for(String columnName: columns ){
                       out.println("<TD>"+columnName+"</TD>");
                    }
                }
                out.println("</TR>");
                //print data
                if(results != null && !results.isEmpty()){
                    for(String[] rowData: results){
                       out.println("<TR align='left'>");
                       for(String data: rowData){
                          out.println("<TD>"+data+"</TD>");
                       }
                       out.println("</TR>");
                    }
                }
            %>
        </TABLE>
    </div>
</body>
</html>
4

1 回答 1

0

调用select *查询时,您是否检查过任何抛出的异常。row[i] = (String) resultSet.getObject(i+1);如果返回的对象不是字符串类型,则此行可能会导致 classCastExceptions。您的numworkers列对我来说似乎是一个整数。

于 2012-12-02T09:26:10.317 回答