开发者

problem in jdbc preparestatement

开发者 https://www.devze.com 2022-12-31 13:21 出处:网络
i am geting error when开发者_C百科 i try to use following,why is it so? ResultSet findByUsername(String tablename,String field,String value)

i am geting error when开发者_C百科 i try to use following,why is it so?

ResultSet findByUsername(String tablename,String field,String value)
{ 
    pStmt = cn.prepareStatement("SELECT * FROM" + tablename +" WHERE ? = ? ");

    pStmt.setString(1,field);
    pStmt.setString(2,value);
    return(pStmt.executeQuery());

}

also i tried following , but its not working too

ResultSet findByUsername(String tablename,String field,String value)
{ 
    String sqlQueryString = " SELECT * FROM " + tablename +" WHERE " + field + "= ? ")     
     pStmt =cn.prepareStatement(sqlQuery);
    pStmt.setString(1, value);
    return(pStmt.executeQuery());

}


You have:

pStmt = cn.prepareStatement("SELECT * FROM" + tablename +" WHERE ? = ? ");
pStmt.setString(1, tablename);
pStmt.setString(2,field);
pStmt.setString(3,value);

Two ?, but attempting to set three parameters.

In fact, you can't set things like names of tables and columns through prepared statement parameters.

You will also need to spell you variable names consistently and do something about the checked exceptions.

(When asking questions about code that causes errors, it's generally a good idea to quote the errors.)


I see two problems here:

  1. "+ tablename +" should be replaced with ?
  2. WHERE ?=? is totally wrong because of the conception of prepared statements. Prepared statements are precompiled statements, refering to the same table('s) and column('s) with different values under criterea (binded values). You can not bind a table or column name (or any other db object).


When using PreparedStatements you are only able to substitute in values, not the names of tables as you've attempts to do with " WHERE ? = ?".

Regarding your second code snippet, apart from the spelling mistake ("filed") I can't see why this would fail. What error are you getting?


On second one try with single code on string value.

String sqlQueryString = " SELECT * FROM " + tablename +" WHERE " + filed + " = ? ");

use single code on comparing string values. Give space between field and equal to.

thanks


In the first one you have 2 parameters in the query but you are adding a third, in the second statement you have a typo...

ResultSet findByUsername(String tablename,String field,String value)
{ 
    pStmt = cn.prepareStatement("SELECT * FROM" + tablename +" WHERE " + field" + = ? ");
    pStmt.setString(1,value);
    return(pStmt.executeQuery());    
}
0

精彩评论

暂无评论...
验证码 换一张
取 消