简体   繁体   中英

Storing MySQL query results in an ArrayList using Java

The following java code takes in a POST request from a JSP file and passes back the out ArrayList as output. The problem I'm having is figuring out how to read the output into the Arraylist properly, so they I can grab each element from the Arraylist and display it in my JSP.

How can I read in the column names as the first array of strings, and then each row of data as the following arrays of strings, so that I have one giant array list that contains the entire results of the query in an organized manner, and will allow me to read the results onto my JSP page?

EDIT: So the only problem I'm having now is that when executing a command like SELECT * FROM table; it only shows the column names. But when I execute a command like SELECT columnName FROM table; it displays the column perfectly. The code below has been updated to reflect where I am at now.

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

Here is my .JSP file, and right now it is only printing [] with nothing in it when I execute a command. I know that commands are working because of previous tests, but the array is not displaying properly.

<?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">
        body{background-color: green;}
    </style>
</head>
<body>
    <h1>This is the MySQL Servlet</h1>
    <form action = "/database/database" method = "post">
    <p>
        <label>Enter your query and click the button to invoke a MySQL Servlet
            <textarea name = "query" cols="20" rows="5"></textarea>
            <input type = "submit" value = "Run MySQL Servlet" />
            <input type = "reset" value = "Clear Command" />
        </label>
    </p>
    </form>
    <hr>
    <TABLE id="results">
        <%
            ArrayList<String> columns = (ArrayList<String>)request.getAttribute("queryColumns");
            ArrayList<String[]> results = (ArrayList<String[]>)request.getAttribute("queryResults"); 
            out.println("<TR>");
            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>");
                   for(String data: rowData){
                      out.println("<TD>"+data+"</TD>");
                   }
                   out.println("</TR>");
                }
            }
        %>
    </TABLE>
    <%= request.getAttribute("query") %>
    <%= request.getAttribute("resultSize") %>
</body>
</html>

Define one list for columns as well.

            ArrayList<String[]> results= new ArrayList<String[]>(); 
            ArrayList<String> columns= new ArrayList<String>();

Populate the list of columns as:

            for(int i = 1; i<= numberOfColumns; i++){
                columns.add(metaData.getColumnName(i));
            }

Populate the list of with results row as:

            while (resultSet.next()){ 
                String[] row = new String[numberOfColumns];
                for (int i = 1; i <= numberOfColumns; i++){
                    row[i] = (String) resultSet.getObject(i);
                }
                results.add(row);
             }

in the end:

            request.setAttribute("queryResults", results);
            request.setAttribute("queryColumns", columns);

First of all, why are you adding a toString call on a String type variable?

Now, as for your issue, I would rather create a Class , for the tables in database, with the columns as attributes. And for each row, create an instance of that class from the columns, and add it to the ArrayList .

So, your ArrayList declaration might be like this: -

List<TargetTable> records = new ArrayList<TargetTable>();

And then: -

while (res.next()) {

    records.add(new TargetTable(res.getString(1), res.getString(2), ...));
}

I hope you know the number of columns in your table.

ArrayList is not the best data structure for this purpose.

You can use

 Table<Integer, String, Object>  

which is available in google guava library. It is really easy to use as well

U can have two arraylists as,

ArrayList<String> columnNames = new ArrayList<String>();
ArrayList<String> out = new ArrayList<String>();

Iterate through ResultSetMetadata and add the columns to the columnNames ArrayList.

Then add the columnNames to out :

out.add(columNames);

Then Create a VO class with all the column names in the table you are accessing. create all the getters and setters for the class names.

Then iterate through the Resultset,

set all the values from the result set into that VO class.

add this VO class to the out arrayList.

ResultVO vo ;
while (resultSet.next()){
vo = new ResultVO();
vo.setColumnName1(resultSet.getString(1));
vo.setColumnName2(resultSet.getString(2));
out.add(vo);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM