-1
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.servlet.ServletException;

public class showdata extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse responce)                                        
        int s=0;
        PrintWriter out = responce.getWriter();
        responce.setContentType("text/html");
        out.println("<html><body>");

I am reading 3 variables t, a, b which I have to use in my oracle query.

String t = request.getParameter("type");       
String a = request.getParameter("about");          
String b = request.getParameter("bird");    
try {
    Class.forName("oracle.jdbc.driver.OracleDriver");  
    Connection con = DriverManager.getConnection(  
        "jdbc:oracle:thin:@localhost:1521:XE","hr","praveen");  
    Statement stmt = con.createStatement();
    out.println("<html>");
    out.println("<body  bgcolor='#56A5EC'>");        
    String query = "select  ****** from  ******* ;

I had to select columns a and b from table t. How to write that variable names a, b, t in above query?

    ResultSet rs = stmt.executeQuery(query);
    catch (Exception e) {
        System.out.println(e.getMessage());
    }
        out.println("</body>"); 
        out.println("</html>");
    }
} 
N00b Pr0grammer
  • 4,503
  • 5
  • 32
  • 46
  • Possible duplicate of [Variable column names using prepared statements](http://stackoverflow.com/questions/3135973/variable-column-names-using-prepared-statements) – Gord Thompson Sep 25 '16 at 13:47
  • @Gord yes it looks very similar. But nobody answered the first post except to say it was bad design. – redcayuga Sep 27 '16 at 19:29

1 Answers1

0

First read the post that Gord Thompson referred to.

The short answer is:

String query = "select " + a +","+ b + " from  " + t ;

However, this leaves you open to sql injection attacks. You need to make sure that the three variables are legal column and table names. Only letters, numbers, underscore or dollar sign allowed.

It would be better if the front end did not pass in the names directly. Instead, pass in a number and the java code would have to "look up" the names.

redcayuga
  • 1,241
  • 6
  • 4