简体   繁体   中英

Multiple sql queries in one connection using java

I'm trying to make different queries in a single db connection but I can't find the way. The query is in function of the wery from the results before. This is the code:

String query_disco="SELECT * FROM disco";
    String name = "";
    String adress="";
    String web="";
    int disco_id=0;

    String query_disco_var="SELECT * FROM disco_var";
    float price=0;
    String style="";
    String hin="";
    String hout="";
    String party_name="";
    int day=0;

    String docType="";
    String docTable="";
    String docBody="";

    Calendar calendar = Calendar.getInstance();     

    try {

        DAO a= new DAO();
        ResultSet b =a.executarSQL(query_disco);            
        day = calendar.get(Calendar.DAY_OF_WEEK);

        docType ="<!DOCTYPE HTML PUBLIC\"--�//W3C//DTD HTML 4.0       " +"Transitional//EN\">\n";
        docBody =
                "<HTML>\n"+
                "<HEAD><TITLE>HelloWorld!</TITLE></HEAD>\n"+
                "<BODY BGCOLOR=\"#FDF5E6\">\n"+
                "<H1>Disco</H1>\n"+
                "<table border=1>"+
                "<tr> <th> name </th> <th> adress </th> <th> web </th> <th> price </th>" +
                "<th> style </th> <th> horari </th> <th> party name </th> </tr>";


        while(b.next()){

            disco_id=b.getInt("disco_id");
            name=b.getString("name");
            adress=b.getString("adress");               
            web=b.getString("web");             

            query_disco_var = query_disco_var + " WHERE disco_id = " + disco_id + " AND day = " + day;
            DAO d= new DAO();
            ResultSet c = d.executarSQL(query_disco_var);
            price=c.getFloat("price");
            style=c.getString("style");
            hin=c.getString("hin");
            hout=c.getString("hout");
            party_name=c.getString("party_name");

            docTable = docTable + "<tr> <td> "+name+" </td> <td> "+adress+" </td> <th>" +web+ "</td> </tr>"+
                       price+ "</td> <td>" +style+ "</td> <td>" +hin+ "-" +hout+ "</td> <td>" +party_name+ "</td> </tr>";
            query_disco_var="SELECT * FROM disco_var";

        } 

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    out.println(docType+docBody+docTable+
            "</table>" +
            "</BODY></HTML>");
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
}

}

The connection with de db works right with this script:

public class DAO {
private Connection connexio;
private Statement sentencia;
/**
 * 
 * @throws Exception
 */
public DAO() throws Exception {
    String user="trmcfunt";
    String password="44445555";
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        connexio=
    DriverManager.getConnection("jdbc:mysql://localhost/iguanaparty_db_test?user="+user+"&password="+password); 
        sentencia=connexio.createStatement();
}
/**
 * 
 * @param query
 * @return
 * @throws SQLException
 */
public ResultSet executarSQL(String query)throws SQLException{
    return sentencia.executeQuery(query);
}

/**
 * 
 * @throws SQLException
 */

public void desconnectarBD() throws SQLException {
sentencia.close();
connexio.close();
}

}

An I'm getting this exepcions:

java.sql.SQLException: Before start of result set
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:854)
at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5772)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5692)
at com.mysql.jdbc.ResultSetImpl.getFloat(ResultSetImpl.java:2615)
at com.mysql.jdbc.ResultSetImpl.getFloat(ResultSetImpl.java:2635)
at controllers.HelloWorld.doGet(HelloWorld.java:87)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)

Regards.

ResultSet c = d.executarSQL(query_disco_var);
price = c.getFloat("price");

Before getting values from a result set, you must call next(), to place the cursor on the first row. Otherwise, as mentioned in the exception, you're before the start of the result set:

ResultSet c = d.executarSQL(query_disco_var);
if (c.next()) {
    price = c.getFloat("price");

Also, learn about prepared statements , because passing parameters to a query by concatenating them makes your code vulnerable to SQL injection attacks, ad will simply break as soon as, for example, one of the string parameters contains a single quote.

Your ResultSet c is never moved to the first result (if any). You should wrap your code reading from c with something like

if (c.next()) {
  // your original code here
} else {
  // whatever you want to do in this case
}

Also, you might have to think about what to do if multiple results are found.

After you execute any SQL the cursor is positioned before the first row. That's why you are getting the execpetion, since there is no data available.

Try a c.next(); after you executed the second SQL query. This will position the cursor on the first result. Remember, if there is no data returned, this call will return false and any subsequent extraction of columns will fail, so you should catch this.

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