简体   繁体   中英

how to add sql parametrized queries through jdbc java

I have to develop a parameterized sql staement something like this below

select * from tablename where cid = cid

so below is the rest service which is calling a method so the user is passing the input parameters like tablename and cid and basis on that it will go to database and to that particular table and will retrieve the coulmn values so below is the code now in the below code please advise how can i change the sql statement to be parametrized so that it will retrieve the value from the table onm the basis of cid input by the user

public String retriveData(@QueryParam("tablename") String tablename,@QueryParam("cid") String cid ) throws SQLException
    {
        Connection con=null;
        PreparedStatement ps=null;
        String statement="";
        String retString="";

        try {
            //Class.forName("com.mysql.jdbc.Driver");
            //put sql jdbc jar in tomcat lib
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  

            con=DriverManager.getConnection("jdbc:sqlserver://xxx:1111; databaseName=aaa", "rr","vvv");
            con.setAutoCommit(false);



            System.out.println("FROM TABLE NAME : "+tablename);// ***** need to be parametrized query basis on the cid ******
                    statement="SELECT * FROM "+tablename+";";// ***** need to be parametrized query basis on the cid ********

            System.out.println("STATEMENT : "+statement);
            ps=con.prepareStatement(statement);
            // Turn use of the cursor on.
            //ps.setFetchSize(50);
            ps.setMaxRows(10);
            ResultSet rs=ps.executeQuery();
            ResultSetMetaData rsmd=rs.getMetaData();
            String name=rsmd.getColumnName(5);
            while(rs.next())
            {

                retString=retString+name+" : "+rs.getString(name)+"<br>";
                System.out.println(retString);

            }

You can't. You need to contruct the sql with string concatenation/placeholder with String.format. prepared statement is for the column values not for table name.

Sources: How to use a tablename variable for a java prepared statement insert

How to pass table name to a Prepared Statement in a SELECT COUNT query?

I'm not sure about why you wanted to parametrized the table name. But parametrized for cid is OK by using the prepared statement like below.

statement="SELECT * FROM " + tablename + " where cid = ?";

preparedStatement.setInt(1, cid);

If you want to retrieve values from specific table by filtering with cid, that will be the answer I guess.

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