问题
If i try to get the timeStamps (Date object) from my mySql database via Java (jdbc) i get the error: "Parameter index out of range (2 > number of parameters, which is 1)."
I can´t find a solution on the internet that works for me, because (i think) the sql-query is correct and i placed the exact number of '?' needed.
PreparedStatement st = conn.prepareStatement("SELECT * FROM timestamp WHERE stampTime BETWEEN '?/0/? 00:00:00.00' AND '?/31/? 23:59:59.999' AND userid = ? ");
st.setInt(1, month);
st.setInt(2, year); //It crashes here
st.setInt(3, month);
st.setInt(4, year);
st.setInt(5, uId);
ResultSet rs = st.executeQuery();
I expect the statement to be prepared and executed but i am reciving the error "Parameter index out of range (2 > number of parameters, which is 1)."
回答1:
Question marks ?
are not interpreted as parameter designators when they are part of a string literal. That is why question marks inside '?/0/? 00:00:00.00'
and '?/31/? 23:59:59.999'
are not counted as parameters of the prepared statement; only the ?
inside userid = ?
is counted, because it is the only one "in the open".
You can fix this problem by constructing the end dates of the range in your Java program, and binding them to parameters inside stampTime BETWEEN ? AND ?
condition.
来源:https://stackoverflow.com/questions/58067934/how-to-fix-parameter-index-out-of-range-2-number-of-parameters-which-is-1