0

Hi I'm using preparedStatement in Java to execute query in DB.

The table:

enter image description here

When it comes to update, delete and insert it's all fine, however when it comes to select( ex. I've done "SELECT ?,?,?,?,? from person" and set strings afterwards) and the following result is returned:

enter image description here

I'm assuming that because it's the strings that are replacing ? so it did not come out as expected:(please correct me if it's wrong)

Expected sql: "SELECT no,name,tel,birthday,address FROM person"

Actual sql: "SELECT \"no\",\"name\",\"birthday\",\"address\" FROM person"

I've tested the second one in in Navicat:

enter image description here

I'd like to understand that why executing this query statement would return a result like this?


If it would help here's Java code:

// Data Assist Object
public class DAO {

    static String jdbcurl;
    static String username;
    static String password;

    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
            ResourceBundle rb = ResourceBundle.getBundle("db");
            jdbcurl = rb.getString("jdbcurl");
            username = rb.getString("username");
            password = rb.getString("password");
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
    }

    // for insert, delete and update
    public int modify(String sql, String[] args){
        int x=0;
        try(Connection con = DriverManager.getConnection( jdbcurl,username ,password);
            PreparedStatement ps = con.prepareStatement(sql);){

            for (int i = 0; i < args.length; i++) {
                ps.setString(i+1, args[i]);
            }

            x =ps.executeUpdate();
            System.out.println(x);

        }catch(SQLException e){
            e.printStackTrace();
        }
        return x;
    }

    // for select
    public List<Map<String,String>> query(String sql, String[] params){

        List<Map<String,String>> resList = new ArrayList<>();
        try(Connection con = DriverManager.getConnection( jdbcurl,username ,password);
            PreparedStatement ps = con.prepareStatement(sql);){

            for (int i = 0; i < params.length; i++) {
                ps.setString(i+1, params[i]);
            }

            try(ResultSet res =ps.executeQuery();){

                ResultSetMetaData mdata = res.getMetaData();
                int num = mdata.getColumnCount();
                while(res.next()){
                    HashMap<String,String> data = new HashMap<>();
                    for (int i = 1; i <= num; i++) {
                        String result = res.getString(i);
                        String columnName = mdata.getColumnName(i);
                        data.put(columnName,result);
                    }
                    resList.add(data);
                }
            }

        }catch(Exception e){
            e.printStackTrace();
        }
        return resList;
    }

    public static void main(String[] args) throws SQLException {
        DAO dao = new DAO();

        String sql = "insert into person(name,tel,birthday,address) values(?,?,?,?)";

        sql = "select ?,?,?,?,? from person";
        List<Map<String,String>> res = dao.query(sql, new String[]{"no","name","tel","birthday","address"});

        for(Map m:res){
            System.out.print("no: "+m.get("no")+",");
            System.out.print("name: "+m.get("name")+",");
            System.out.print("tel: "+m.get("tel")+",");
            System.out.print("birthday: "+m.get("birthday")+",");
            System.out.println("address: "+m.get("address"));
        }

    }
}

Thanks for any help.

3
  • Why are you trying to construct the columns like this? Jul 28, 2017 at 1:38
  • @AdrianShum I'm practicing sql syntax so the data are just random alphabets and numbers. If there's suggestions on constructing columns I'd like to know, thanks.
    – Yumi Chen
    Jul 28, 2017 at 1:50
  • Normally columns are defined statically (There is of course ways to construct it dynamically, but not with statement parameters). i.e. it should be just select no, name, tel, birthday, address from person Jul 28, 2017 at 1:53

2 Answers 2

2

SQL basically works on a show me these columns where this criteria is true basis.

In the statement:

"SELECT \"no\",\"name\",\"birthday\",\"address\" FROM person"

You're getting

SELECT "no", "name", "birthday", "address" FROM person

when it actually hits the database. The "" operator creates a string in SQL. In plain English, that means that you're telling the database to return that specified set of strings for each row in person where the criteria you listed is met.

Since you didn't list a where clause, all rows are true by default so you get one row of strings for every single row in the person table. The first query is the same thing, but instead of directly passing the strings, you're adding them in as bind variables.

If you actually want to see the values in the table, write the query without the "'s

SELECT no, name, birthday, address FROM person

Unless otherwise specified, bind functions generally pass the value as a string. Which is why the query behaved the way it did. I don't recommend using bind variables in the select clause. That's a strange practice.

Edit:

As Adrian pointed out in the comments, " denotes columns in SQL. My apologies for not catching that. I assume that you meant to use the ' operator which actually denotes strings.

If not, something else is going on here entirely.

3
  • several problem in your answer: 1. select ? from x with parameter 1 set to foo is not necessary (and most like not) going to produce the sql select "foo" from x. 2. in SQL standard, we use single quote for strings. 3. Double quote have different meaning in different DBMS. For example, in Oracle, select "foo" from x, "foo" is still a column name instead of string value. I understand these are based on OP's (wrong) statements. However I think that should be corrected instead of answering based on his wrong statements :) Jul 28, 2017 at 2:04
  • @AdrianShum: That's a good catch. I completely overlooked that while I was writing my answer. I've added an update.
    – Jacobm001
    Jul 28, 2017 at 2:30
  • Thank you. Things are clarified for me.
    – Yumi Chen
    Jul 28, 2017 at 4:26
0

For the select you use the question marks in the WHERE clause, not where you list the fields you need as output.

Replace

sql = "select ?,?,?,?,? from person";

with

sql = "select no,name,tel,birthday,address from person";

For this particular query there is no binding to do. It will retrieve all the records from the table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.