Error in SQL syntax for Prepared Statement? [duplicate] - java

This question already has answers here:
SQL 1064 Syntax Error using a JDBC prepared statement
(3 answers)
Closed 6 years ago.
I'm trying to run a prepare statement and get an error in MySQL syntax. Not sure what is the error?
Code:
PreparedStatement stmt = null;
conn = ds.getConnection();
String query = "select distinct FName from PRL p1, RequestView p2 where p1.RequestId = p2.RequestId and p1.PackageId = p2.PackageId and p1.ProductId = ? and p1.ProductNumber = ? and p1.Version = ? order by p2.ArtName";
stmt = conn.prepareStatement(query);
stmt.setString(1,id);
stmt.setString(2,num);
stmt.setString(3,ver);
rs = stmt.executeQuery(query);
Error:
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: 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 '? and p1.ESTProductMatNumber =? and p1.Version =? order by p2.ArtworkName' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)

Never mind. I figured it out. rs = stmt.executeQuery(query); has to be rs = stmt.executeQuery();

Related

I have a sql error java.sql.SQLException: Operation not allowed for a result set of type ResultSet.TYPE_FORWARD_ONLY [duplicate]

This question already has answers here:
ResultSet: Exception: set type is TYPE_FORWARD_ONLY -- why?
(9 answers)
Closed 20 days ago.
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/onlineshop?autoReconnect=true&useSSL=false","root",DatabaseConnection.root);
PreparedStatement ps=con.prepareStatement("select * from custinfo");
ResultSet rs=ps.executeQuery();
/*******
//for counting the number of rows in result set
if(rs.last()) {
x=rs.getRow();
rs.beforeFirst();
}
When I'm trying to execute it it showing me the error:
java.sql.SQLException: Operation not allowed for a result set of type
ResultSet.TYPE_FORWARD_ONLY.
Can you help me how can I solve this?
The error message says it all - the ResultSet is of TYPE_FORWARD_ONLY, so you can't scroll it back with beforeFirst(). Having said that, querying the entire table (and having to send all that data from the database to your application) just to get its size is probably not a good practice. It would be much easier to use an aggregate query to get the number of rows:
try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/onlineshop?autoReconnect=true&useSSL=false","root",DatabaseConnection.root);
PreparedStatement ps = con.prepareStatement("select count(*) from custinfo");
ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
size = rs.getInt(1);
}
}

JAVA JDBC mySql Prepared statement Update query [duplicate]

This question already has answers here:
MySQLSyntaxErrorException near "?" when trying to execute PreparedStatement
(2 answers)
Closed 4 years ago.
I am trying to execute the following code
package jdbclesson;
import java.sql.*;
public class PreparedQuery {
public static void main(String[] args) throws Exception
{
String url = "jdbc:mysql://localhost:3306/alien?useSSL=false";
String uname = "root";
String pass = "ma123";
String query = "UPDATE student SET username= ? where userid= ? ";
PreparedStatement stmt = null;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uname, pass);
stmt = con.prepareStatement(query);
stmt.setString(1, "tina");
stmt.setInt(2, 6);
int rs = stmt.executeUpdate(query);
System.out.println(rs);
stmt.close();
con.close();
}
}
but getting following errors
Exception in thread "main"
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '? where
userid=?' at line 1
My database has only 1 table student with 2 columns userid and username and 10 rows what m i missing
Try:
int rs = stmt.executeUpdate();
Instead of:
int rs = stmt.executeUpdate(query);
executeUpdate() runs the query of the prepared statement, which is what you want. executeUpdate(query) runs the query passed to the method. You were getting the error because you were passing an SQL with errors (contains ?).
Please try:
"UPDATE student SET username= ? ” + ” where userid= ?";
int rs=stmt.executeUpdate();

Getting error in Select from MYSQL

Getting error in Select from MYSQL on the line ResultSet rs = st.executeQuery(fetch_title);
Error msg : 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 ':09:53' at line 1
String test = "27-May-2016 11:09:53";
String fetch_title = "SELECT title FROM competitor_analysis WHERE cron_date_time="+test+"";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(fetch_title);
Wrap up your date in speech marks in the query.
String fetch_title = "SELECT title FROM competitor_analysis WHERE cron_date_time='"+test+"'";
You have to declare the string in your MySQL query as a string; you aren't doing this which results in the error.
So you need to insert in '' in your case.
So you could do it like this:
String fetch_title = "SELECT title FROM competitor_analysis WHERE cron_date_time='"+test+"'";
Your code is unsafe because it is conducive to SQL Injection attacks, you need to use a PreparedStatement instead as next:
String test = "27-May-2016 11:09:53";
PreparedStatement ps = connection.prepareStatement(
"SELECT title FROM competitor_analysis WHERE cron_date_time=?"
);
ps.setString(1, test);
ResultSet rs = ps.executeQuery();
This approach has 2 main advantages:
It is safer as mentioned above
It is less error prone, as you don't have to escape the value explicitly anymore since it will be managed by the driver itself

PreparedStatement throws syntax error [duplicate]

This question already has answers here:
MySQLSyntaxErrorException near "?" when trying to execute PreparedStatement
(2 answers)
Closed 7 years ago.
Im preparing a query using PreparedStatements and it runs fine when i hardcode te query with the condition parameter.
but throws error , if the parameter is passed from setString() method.
com.mysql.jdbc.JDBC4PreparedStatement#2cf63e26: select * from linkedin_page_mess ages where company_id = '2414183' com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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
In the error log, above my query looks fine.
public JSONObject getLinkedInMessages(String compId)
{
linlogger.log(Level.INFO, "Called getLinkedInMessages method");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
JSONObject resObj = new JSONObject();
JSONArray tempArray = new JSONArray();
try
{
conn = InitOrGetConnection();
String query = "select * from linkedin_page_messages where company_id = ?";
PreparedStatement pst=conn.prepareStatement(query);
pst.setString(1, compId);
System.out.println("\n\n"+pst.toString());
rs= pst.executeQuery(query);
// process resultset logics
}
catch(Exception e)
{
System.out.println(e);
linlogger.log(Level.INFO, "Exception occured "+e.toString());
}
}
Is there anything wrong with the PreparedStatements?
Remove the parameter from
rs= pst.executeQuery(query);
change to
rs= pst.executeQuery();
If you pass query in pst.executeQuery(query); as parameter then this passed query string take priority over the query string you passed in conn.prepareStatement(query); and since in query(select * from linkedin_page_messages where company_id = ?) you dint pass parameter you get the error.
remove the parameter in this line:
rs= pst.executeQuery(query);
It must be
rs= pst.executeQuery();
Because the statement is prepared at PreparedStatement pst=conn.prepareStatement(query);
execute(String sql) is inherited from Statement and will execute the satement (sql) without prepared it.

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