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();
Related
This question already has answers here:
MySQLSyntaxErrorException near "?" when trying to execute PreparedStatement
(2 answers)
Closed 3 years ago.
I am doing an insertion in a mysql database through a jdbc connection, which connects perfectly, that if when I do the PreparedStatement, Tomcat throws me a sql error that says the following:
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 '?,?,?)' at line 1
The question is that when I do the query through a statement, it performs the query without any problem, which makes me suspect that the error is actually in the PreparedSatement. Here I leave the code.
#Override
public void save(Planet planet) throws SQLException {
String namePlanet = planet.getName();
float massPlanet = planet.getMass();
boolean habitablePlanet = planet.isHabitable();
sql = "INSERT INTO planeta (nom,massa,habitable) VALUES (?,?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, namePlanet);
preparedStatement.setFloat(2, massPlanet);
preparedStatement.setBoolean(3, habitablePlanet);
preparedStatement.executeUpdate(sql);
}
I will also leave the code with the preparedstatement, so you can see that this does work.
#Override
public void save(Planet planet) throws SQLException {
String namePlanet = planet.getName();
float massPlanet = planet.getMass();
boolean habitablePlanet = planet.isHabitable();
sql = "insert into planeta(nom,massa,habitable) value('" + namePlanet + "'," + massPlanet + "," + habitablePlanet + ")";
stmt.executeUpdate(sql);
}
Please be patient with me, I'm a student and thanks in advance.
Like #Jens told in the comments i have to call executeUpdate() without parameters.
Thx again #Jens!!
Thats the correct code:
#Override
public void save(Planet planet) throws SQLException {
String namePlanet = planet.getName();
float massPlanet = planet.getMass();
boolean habitablePlanet = planet.isHabitable();
sql = "INSERT INTO planeta (nom,massa,habitable) VALUES (?,?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, namePlanet);
preparedStatement.setFloat(2, massPlanet);
preparedStatement.setBoolean(3, habitablePlanet);
preparedStatement.executeUpdate(); // <--- Here was the error!!
}
This question already has answers here:
Is it possible to supply parameters for table or column name in Prepared Statements or QueryRunner.update()?
(1 answer)
Using Prepared Statements to set Table Name
(8 answers)
How to use a tablename variable for a java prepared statement insert [duplicate]
(4 answers)
Closed 5 years ago.
So I have this following method which works just fine:
static void getCount(final String url, final String username, final String password) throws SQLException {
final Connection connection = DriverManager.getConnection(url, username, password);
final String query = "SELECT COUNT(*) FROM app_user";
final PreparedStatement preparedStatement = connection.prepareStatement(query);
final ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
System.out.println(resultSet.getInt(1));
resultSet.close();
preparedStatement.close();
connection.close();
}
but when I try:
static void foobar(final String url, final String username, final String password, final String tablename) throws SQLException {
final Connection connection = DriverManager.getConnection(url, username, password);
final String query = "SELECT COUNT(*) FROM ? ";
final PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, tablename);
final ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
System.out.println(resultSet.getInt(1));
resultSet.close();
preparedStatement.close();
connection.close();
}
I get:
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 ''app_user'' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
What am I doing wrong?
You can only bind values in a PreparedStatement, not syntactic elements or object names (in this case, the table name). You'll have to resort to string manipulation:
final String query = String.format("SELECT COUNT(*) FROM %s", tablename);
final PreparedStatement preparedStatement = connection.prepareStatement(query);
final ResultSet resultSet = preparedStatement.executeQuery();
Note that there are no placeholders in this query, so it's questionable whether there's really any advantage in using a PreparedStatement as opposed to a plain old Statement.
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();
I am having a problem in executing a simple select statement in Microsoft Sql Server DB using a Java program. I am facing below 2 issues,
Code by using statement * Resultset - program just hungs near the executequery() method and no progress after that.
Sample code:-(Full code pasted below)
Statement sta = conn.createStatement();
String Sql3 = "select name from dbo.network";
sta.executeQuery(Sql3);
ResultSet rs=sta.getResultSet();
code with preparestatment * Resultset throws error saying
The method executeQuery() cannot take arguments on a PreparedStatement or CallableStatement
Sample Code:-
PreparedStatement ps = conn.prepareStatement(Sql3);
ResultSet rs = ps.executeQuery(Sql3);
Complete Code:-
public class DbConnectionTest {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
System.out.println("Entered into main method");
String userName ="***";
String password ="***";
String url ="jdbc:sqlserver://****:1433;databaseName=***";
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);
System.out.println("test");
Statement sta = conn.createStatement();
String Sql3 = "select name from dbo.network";
//PreparedStatement ps = conn.prepareStatement(Sql3);
//ResultSet rs = ps.executeQuery(Sql3);
sta.executeQuery(Sql3);
//sta.getMoreResults();
//sta.getMoreResults();
ResultSet rs=sta.getResultSet();
if(rs != null)
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}catch(Exception se){
//Handle errors for JDBC
se.printStackTrace();
}
}
}
In Addition, I confirm the below,
Same query executes fine in the database.
SQL Browser Server service is running fine
TCP/IP is enabled
Credentials and the URL string are correct
sqljdbc4.jar is used.
Please help me with this issue.
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.