error on placeholder (?,?) [duplicate] - java

This question already has answers here:
MySQLSyntaxErrorException when trying to execute PreparedStatement [duplicate]
(2 answers)
Closed 7 years ago.
I am trying to pass string array and int array to database. Code I am trying is below, but this always shows the error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?)' at line 1
Connection connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/javabase", "java", "password");
CompareAndCount compareAndCount = new CompareAndCount();
ReadWord bagOfWords = new ReadWord();
String[] listOfWords = bagOfWords.openFile();
int[] count =compareAndCount.compareWords();
for (int i = 0; i < listOfWords.length; i++) {
String query = "INSERT INTO angry(tagwords,termfrequency) VALUES(?,?)";
PreparedStatement pStmnt = (PreparedStatement) connection.prepareStatement(query);
pStmnt.setString(1, listOfWords[i]);
pStmnt.setLong(2, count[i]);
pStmnt.executeUpdate(query);
}
connection.close();

Replace
pStmnt.executeUpdate(query);
by
pStmnt.executeUpdate();
And prepare the statement once, before the loop, instead of re-preparing it again and again at each iteration.

Related

How to Fix MySQL Count Function Error In Java? [duplicate]

This question already has answers here:
How to use a tablename variable for a java prepared statement insert [duplicate]
(4 answers)
Closed 6 months ago.
I am trying to create a method that will count the number of records I have in a certain table when the method is called. But for some reason, I keep getting an error saying I have a problem in my SQL code. Looking over everything, I couldn't find the problem. I even went as far to as to copy parts of another person's solution online, but this failed too. To better show where the error seems to be ocurring, I inserted two print statements in the code. I think Java and SQL must hate me! Any help would be most appreciated.
int tableCounter(String tableName) {
int num = 0;
String sql = "SELECT COUNT(*) AS total FROM ?";
try(Connection conn = letConnect(); PreparedStatement ps = conn.prepareStatement(sql)){
ps.setString(1, tableName);
System.out.println("test");
ResultSet rs = ps.executeQuery();//error ocurrs here
//when the SQL code is executed
System.out.println("test");
num = rs.getInt("total");
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}
Output:
test
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Country'' at line 1
at mysql.connector.java#8.0.30/com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at mysql.connector.java#8.0.30/com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at mysql.connector.java#8.0.30/com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:916)
at mysql.connector.java#8.0.30/com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:972)
at Database_Interactor.tableCounter(Database_Interactor.java:25)
at MainClass.main(MainClass.java:10)
Based on the answer given above, the code should look something like this:
int tableCounter(String tableName) {
int num = 0;
String sql = "SELECT COUNT(*) AS total FROM "+ tableName;
Connection conn = letConnect();
try{Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()){
num = rs.getInt("total");}
}catch (SQLException e) {
e.printStackTrace();}
return num;}

How to pass ArrayList<> as IN clause in SQL query in MySQL [duplicate]

This question already has an answer here:
Passing an Array to a SQL query using Java's PreparedStatement
(1 answer)
Closed 7 years ago.
I am using mySQL JDBC driver in my java program. I want to pass a ArrayList in the IN clause in my SQL query.
i did use a prepared statement like this, but this throws an
"java.sql.SQLFeatureNotSupportedException"exception
since mysql doesn't support this.
ArrayList<String> list = new ArrayList<String>();
PreparedStatement pstmt =
conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", list.toArray());
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();
Is there any other way to do this ? Maybe with Statement stmt.
Build the SQL statement with the correct number of markers, and set all the values.
Beware: Databases have a limit to the number of parameters allowed, though it's very high for MySQL (65535).
char[] markers = new char[list.size() * 2 - 1];
for (int i = 0; i < markers.length; i++)
markers[i] = (i & 1 == 0 ? '?' : ',');
String sql = "select * from employee where id in (" + markers + ")";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int idx = 1;
for (String value : list)
stmt.setString(idx++, value);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
// code here
}
}
}

java: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' [duplicate]

This question already has an answer here:
JDBC returning MySQLSyntaxError Exception with correct statement
(1 answer)
Closed 7 years ago.
i want to search a value in my data base and return it i made this function but it returns always 0 the result set doesn"t respond
here is the function:
public int getNat() throws Exception{
String query = "SELECT code_nat FROM nationalite WHERE nationalite=? ";
try ( PreparedStatement stat = cnx.prepareStatement(query) ) {
stat.setString(1, (String)cmbNat.getSelectedItem());
rslt = stat.executeQuery(query);
return rslt.getInt(1);
}catch(SQLException ex){
ex.printStackTrace();
return 0;
}
}
and here is the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?'
Change
rslt = stat.executeQuery(query);
to
rslt = stat.executeQuery();
When using a PreparedStatement, you don't pass the SQL query to executeQuery, since the prepared statement already contains the SQL statement and the parameters you passed to it.
In addition, you must call rslt.next() before accessing the ResultSet.
To summarize :
stat.setString(1, (String)cmbNat.getSelectedItem());
rslt = stat.executeQuery();
Integer foo = null;
if (rslt.next())
foo = rslt.getObject("foo") != null ? rslt.getInt("foo") : null;
return foo;

jdbc error Parameter index out of range (2 > number of parameters, which is 1) [duplicate]

This question already has answers here:
java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) [closed]
(2 answers)
Closed 6 years ago.
I wrote following java method and when I call it, gives me the error
Parameter index out of range (2 > number of parameters, which is 1).
it is giving error at line preparedStatement.setInt(2,p);
for(int t=0;t<2 & exit;t++){
sql="SELECT allocationProb FROM trial.teacherallocation where TeacherID=?;";
preparedStatement = dbConnection.prepareStatement(sql);
preparedStatement.setString(1,var1[t]);
ResultSet rs3=preparedStatement.executeQuery();
rs3.next();
int allocationProb=rs3.getInt(1);
rs3.close();
System.out.println("INSIDE");
int p=0;
if(allocationProb==0){
p=1;
sql="UPDATE `trial`.`teacherallocation` SET `AllocationSub1`=?,` allocationProb`=? WHERE `TeacherID`=?;";
preparedStatement.setString(1,str1);
preparedStatement.setInt(2,p);
preparedStatement.setString(3,var1[t]);
preparedStatement.executeUpdate();
}
}
Although you change your sql variable
sql="UPDATE `trial`.`teacherallocation` SET `AllocationSub1`=?,` allocationProb`=? WHERE `TeacherID`=?;";
you don't create a new PreparedStatement with it. So when you call
preparedStatement.setString(1,str1);
preparedStatement.setInt(2,p);
preparedStatement.setString(3,var1[t]);
preparedStatement.executeUpdate();
you're calling it on the SQL
sql="SELECT allocationProb FROM trial.teacherallocation where TeacherID=?;";
which only has 1 parameter and will throw an exception if you try to add more.
You need to create a new or reassign a PreparedStatement object before those lines.
sql="UPDATE `trial`.`teacherallocation` SET `AllocationSub1`=?,` allocationProb`=? WHERE `TeacherID`=?;";
preparedStatement = dbConnection.prepareStatement(sql);
preparedStatement.setString(1,str1);
preparedStatement.setInt(2,p);
preparedStatement.setString(3,var1[t]);
preparedStatement.executeUpdate();
Also you should close all jdbc connections when you are done with them.
preparedStatement.close();
You are using same prepared statement for two different SQL statements. And No of parameters is different as well. That's why you are getting this error.
Try following
if(allocationProb==0){
p=1;
preparedStatement = dbConnection.prepareStatement(sql);
Hope it helps

JDBC Problem wth select where query [duplicate]

This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
Closed 5 years ago.
My Code:
con = jdbc.connect();
System.out.println("status of con"+con);
String query = " select * from BmgCPUTotalUsage where CPUserID='"+CPUserID+"' and MessageTypeID='"+MessageTypeID+"'";
System.out.println(query);
PreparedStatement statement = con.prepareStatement(query);
ResultSet result = statement.executeQuery();
System.out.println(result);
int QuotaUsed=result.getInt("QuotaUsed");
Output:
status of concom.mysql.jdbc.JDBC4Connection#182600f
select QuotaUsed from BmgCPUTotalUsage where CPUserID='msdp' and MessageTypeID='SMS'
com.mysql.jdbc.JDBC4ResultSet#16e1dd8
java.sql.SQLException: Before start of result set.
Can anybody please say me how can I remove this exception.and fetch the QuotaUsed from the table.where QuotaUsed is an integer.
You really need to do more reading of the JDBC Tutorial, but briefly, try this:
ResultSet resultSet = statement.executeQuery();
if (resultSet.next() {
int quotaUsed = resultSet.getInt("QuotaUsed");
}

Categories