Variable column names using prepared statements

后端 未结 7 642

I was wondering if there was anyway to specify returned column names using prepared statements.

I am using MySQL and Java.

When I try it:

St         


        
相关标签:
7条回答
  • 2020-11-22 08:42

    Below is the solution in java.

    String strSelectString = String.format("select %s, %s from %s", strFieldName, strFieldName2, strTableName);
    
    0 讨论(0)
  • 2020-11-22 08:48

    This indicates a bad DB design. The user shouldn't need to know about the column names. Create a real DB column which holds those "column names" and store the data along it instead.

    At any way, no, you cannot set column names as PreparedStatement values. You can only set column values as PreparedStatement values

    If you'd like to continue in this direction, you need to sanitize the column names (to avoid SQL Injection) and concatenate/build the SQL string yourself. Quote the separate column names and use String#replace() to escape the same quote inside the column name.

    0 讨论(0)
  • 2020-11-22 08:48

    The accepted answer is not actually correct. While the OP approach indicated a bad DB design, it might be required by the business logic (for instance a MySQL IDE)

    Anyway, for MySQL prepared statements, what you need to know is that ? is for values, but if you need to escape column names, table names etc, use ?? instead.

    Something like this will work:

    SELECT ??, ??, ?? FROM ?? WHERE ?? < ? 
    

    Set values to ['id', 'name', 'address', 'user', 'id', 100]

    0 讨论(0)
  • 2020-11-22 08:53

    I think this case can't work because the whole point of the prepared statement is to prevent the user from putting in unescaped query bits - so you're always going to have the text quoted or escaped.

    You'll need to sanitize this input in Java if you want to affect the query structure safely.

    0 讨论(0)
  • 2020-11-22 08:54

    Use sql injection disadvantage of Statement Interface as advantage. Ex:

    st=conn.createStatement();
    String columnName="name";
    rs=st.executeQuery("select "+ columnName+" from ad_org ");
    
    0 讨论(0)
  • 2020-11-22 08:55
    public void MethodName(String strFieldName1, String strFieldName2, String strTableName)
    {
    //Code to connect with database
    String strSQLQuery=String.format("select %s, %s from %s", strFieldName, strFieldName2, strTableName);
    st=conn.createStatement();
    rs=st.executeQuery(strSQLQuery);
    //rest code
    }
    
    0 讨论(0)
提交回复
热议问题