-1

this is my current java program. I need to make a prepared statement and connect to a MySql database.

 try {
        Connection connect = DriverManager.getConnection(host, username, password);
        System.out.println("works fine connected");

        /*
         * 
         * */
        String Dquery  = ("SELECT * FROM ?"); 

        //create the java statement
        PreparedStatement st = connect.prepareStatement(Dquery);
        st.setString(1, "lmgs_Book");


        System.out.println("mySql statemnt: "+Dquery);

        //execute the query, and get a java resultset
        ResultSet rs = st.executeQuery();

        //iterate through the java resultset
        while (rs.next())
        {
            String id = rs.getString(Column1);
            String firstName  = rs.getString(Column2);/*
            String lastName = rs.getString(Column3);
            String dateCreated = rs.getString(Column4);
            int isAdmin = rs.getInt (Column5);*/

            //print the results
            System.out.println(id+"|\t"+firstName/*+"|\t\t"+lastName+"|\t\t"+dateCreated+"|\t"+isAdmin*/);
        }
        st.close();


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

I cant insert the "lmgs_Book" String into the prepared statement.

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54

2 Answers2

2

Prepared statement is for the column values not for table name.

But you can use placeholder in place of table name and then replacing that with your tablename.

 String Dquery  = ("SELECT * FROM $tableName");
 Dquery = Dquery.replace("$tableName","lmgs_Book");
 PreparedStatement st = connect.prepareStatement(Dquery); 

 Remove this:
 st.setString(1, "lmgs_Book");

Caution:

And what is the advantage compared to

String Dquery = "SELECT * FROM lmgs_Book";? [Recommended]

Answer: No advantage at all. You may embrace potential harms if you use placeholder in table name like above.

(especially since you should not use a variable in the replace call instead of the literal, since that might make the statement vulnerable to SQL injection)

1000111
  • 13,169
  • 2
  • 28
  • 37
  • Yes you are right. No advantage at all. But I just wanted the question owner perceive the use of prepared statement. @AndreasFester – 1000111 Mar 08 '16 at 06:20
  • And thanks for your valuable comment. I am gonna put that comment in **Caution** Section of my post. Thanks again @AndreasFester – 1000111 Mar 08 '16 at 06:22
0

try this and Please make sure your queryString column Name must be a varchar in your database.

    String Dquery  = ("SELECT * FROM tablename where column_name =?"); 

    //create the java statement
    PreparedStatement st = connect.prepareStatement(Dquery);
    st.setString(1, "lmgs_Book");  //this line will be set Imgs Books as search Parameter.
Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52