JDBC MySql bind variable syntax error in where clause - java

I am getting this error:
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
public static Person getDetails(int id) {
Connection conn = null;
PreparedStatement stmt = null;
Person newPerson = new Person();
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
String sql = "SELECT firstName, lastName, birthday FROM person WHERE id=?";
System.out.println("SQL Statement:\n\t" + stmt);
stmt = conn.prepareStatement(sql);
System.out.println("Prepared Statement before bind variables set:\n\t" + stmt.toString());
//Bind values into the parameters.
System.out.println("ID " + id);
stmt.setInt(1, id); // This would set id
System.out.println("Prepared Statement after bind variables set:\n\t" + stmt.toString());
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
Date birthday = rs.getDate("birthday");
newPerson.setBirthday(birthday);
newPerson.setFirstName(firstName);
newPerson.setLastName(lastName);
newPerson.setId(id);
//Display values
System.out.print("ID: " + id);
System.out.print(", First: " + firstName);
System.out.println(", Last: " + lastName);
System.out.println(", Birthday: " + birthday);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
return newPerson;
}
I have success executing the query without the where clause. I have looked at many examples and nothing I try fixes this.

Don't use executeQuery(String) with prepared statements...
Instead of....
ResultSet rs = stmt.executeQuery(sql);
use...
ResultSet rs = stmt.executeQuery();
Take a look at How to use Prepared Statements for more details

If I understand your question, the problem is you used Statement.executeQuery(String). I'm fairly certain you meant to use PreparedStatement.executeQuery(),
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(sql); // <-- adding sql here makes it use the
// Statement version.
You wanted to use
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(); // <-- use the version from PreparedStatement

Change
ResultSet rs = stmt.executeQuery(sql);
to
ResultSet rs = stmt.executeQuery();

Related

How to write sql query in an executeQuery method?

I have an account_holder table with a field userId and I have a data set as data.I want to select only that record from account_holder which having userId as data[3] i.e (4 field of data set). I am writing query as:
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from account_holder where userID = 'data[3]' ");
But my rs is null the entry not gets in to the ResultSet object rs. Plz tell me the correct way to write sql query with where clause inside the executeQuery() method.
As the first post said this is one way of handling this:
try {
Statement statement = connection.createStatement(); // Creating Statement
// Executing Statement
ResultSet resultSet = statement.executeQuery("SELECT * FROM account_holder WHERE userID = '" + data[3] + "'");
// Check if result set has entries
if (resultSet.first()) // If so the user already exists
System.out.println("User already exists! " + resultSet.getString("userID"));
else // If not the user does not exist
System.out.println("User does not exist!");
// Clean up
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
But in your context I would actually recommend using a PreparedStatement:
try {
// Making statement
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM account_holder WHERE userID = ?");
preparedStatement.setString(1, data[3]); // Set String for the first question mark in Query
ResultSet resultSet = preparedStatement.executeQuery(); // Executing the Prepared Statement
// Check if result set has entries
if (resultSet.first()) // If so the user already exists
System.out.println("User already exists! " + resultSet.getString("userID"));
else // If not the user does not exist
System.out.println("User does not exist!");
// Clean up
resultSet.close();
preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
You have to only change the query in the executeQuery method
example:
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from account_holder where userID = '"+data[3]+"' ");
or you can also run the following command:
ResultSet rs = st.executeQuery("select * from account_holder where userID = "+data[3]+"");

java oracle jdbc resultset empty but record is available in the table

I'm running java 1.8 connecting to oracle 12c using ojdbc7.jar for jdbc connection.
This is the code that execute to retrieve the data
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#" +
ipAddress + ":1521:" + dbname,userName,password);
Statement stmt=con.createStatement();
String query = "select * from table_name";
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
System.out.println(rs.getString(1));
}
but the code is not entering the while loop.
When i try exeuction the same query in DB, I could see the table has 10 entries.
Does anyone know what could be the reason?
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#" +
ipAddress + ":1521:" + dbname,userName,password);
Statement stmt = con.createStatement();
String query = "select * from table_name";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException e ) {
} finally {
if (stmt != null) { stmt.close(); }
}

Java Sql Statement Unknown column id

My database is MySQL run from xampp
I have 3 colums id,nazwa,kwota
I keep getting an error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown
column 'main' in 'field list'
I think problem is with the
String sql = ("SELECT id, nazwa, kwota");
ResultSet rs = stmt.executeQuery(sql);
but I was looking for almost 2 hours and does not seem to find the answer...
Im desperate, thank you
import java.sql.*;
import javax.sql.*;
public class JdbcDriver{
public static void main(String args[]) {
Connection conn = null;
Statement stmt = null;
String username = "wojtek";
String password = "3445222";
String url = "jdbc:mysql://localhost:3306/javatest";
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(url, username, password);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = ("SELECT id, nazwa, kwota");
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String nazwa = rs.getString("nazwa");
int kwota = rs.getInt("kwota");
//Display values
System.out.print("ID: " + id);
System.out.print(", Nazwa: " + nazwa);
System.out.print(", kwota: " + kwota);
}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
That's a weird wrong SQL statement as pointed below. It's missing FROM table_name
String sql = ("SELECT id, nazwa, kwota");
It should be
String sql = ("SELECT id, nazwa, kwota FROM your_table_name");
^... missing this part
Table is missing in the statement. Better way is always test the query in the database editor before using it.
We always pass SQL Statement in a String in java. If the Statement is Wrong the java compiler gives us an Exception. Same is the case with you, you have passed statement through string. But you have not specified the table from which you are retriving you data.
Your String is:
String sql = ("SELECT id, nazwa, kwota");
You should write the String as:
String sql = ("SELECT id, nazwa, kwota FROM table");
Here table is your table Name from which you are retriving your data.

How can I retrieve the maximum value of a MySQL primary key in JDBC?

I'm working on this code but it ain't working. I've put another query which is working but not this one. Help will be much appreciated.
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con1 = null;
con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/itcomplaintsystem", "root", "colbiecaillat");
Statement stmt = con1.createStatement();
ResultSet rs = stmt.executeQuery("SELECT MAX(PHONE) FROM complaints");
if(rs != null)
{
while(rs.next())
{
String cno=rs.getString("C_NO");
out.println(cno);
}
}
stmt.close();
rs.close();
con1.close();
}
catch(Exception e){
out.println(e);
}
In your query
SELECT MAX(PHONE) FROM complaints
you are not assigning an alias to the result. These functions usually return random or default column names, so when you perform
String cno=rs.getString("C_NO");
the C_NO column does not exist on the result set.
To fix it, fix your query like this
SELECT MAX(PHONE) as C_NO FROM complaints
With as C_NO I am giving this column the alias name you are trying to get.
Your select part of the query does not have C_NO , If you need max phone then your query will be:
SELECT MAX(PHONE) as max_phone FROM complaints
assuming that phone is long your complete code will be :
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con1 = null;
con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/itcomplaintsystem", "root", "colbiecaillat");
Statement stmt = con1.createStatement();
ResultSet rs = stmt.executeQuery("SELECT MAX(PHONE) as max_phone FROM complaints");
if(rs != null)
{
while(rs.next())
{
Long cno=rs.getLong("max_phone");
out.println(cno);
}
}
stmt.close();
rs.close();
con1.close();
}
catch(Exception e){
out.println(e);
}

Problems with PreparedStatement - Java

Im trying to use PreparedStatement to my SQLite searches. Statement works fine but Im getting problem with PreparedStatement.
this is my Search method:
public void searchSQL(){
try {
ps = conn.prepareStatement("select * from ?");
ps.setString(1, "clients");
rs = ps.executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
but Im getting this error:
java.sql.SQLException: near "?": syntax error at
org.sqlite.DB.throwex(DB.java:288) at
org.sqlite.NestedDB.prepare(NestedDB.java:115) at
org.sqlite.DB.prepare(DB.java:114) at
org.sqlite.PrepStmt.(PrepStmt.java:37) at
org.sqlite.Conn.prepareStatement(Conn.java:231) at
org.sqlite.Conn.prepareStatement(Conn.java:224) at
org.sqlite.Conn.prepareStatement(Conn.java:213)
thx
Columns Parameters can be ? not the table name ;
Your method must look like this :
public void searchSQL()
{
try
{
ps = conn.prepareStatement("select * from clients");
rs = ps.executeQuery();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
Here if I do it like this, it's working fine, see this function :
public void displayContentOfTable()
{
java.sql.ResultSet rs = null;
try
{
con = this.getConnection();
java.sql.PreparedStatement pstatement = con.prepareStatement("Select * from LoginInfo");
rs = pstatement.executeQuery();
while (rs.next())
{
String email = rs.getString(1);
String nickName = rs.getString(2);
String password = rs.getString(3);
String loginDate = rs.getString(4);
System.out.println("-----------------------------------");
System.out.println("Email : " + email);
System.out.println("NickName : " + nickName);
System.out.println("Password : " + password);
System.out.println("Login Date : " + loginDate);
System.out.println("-----------------------------------");
}
rs.close(); // Do remember to always close this, once you done
// using it's values.
}
catch(Exception e)
{
e.printStackTrace();
}
}
Make ResultSet a local variable, instead of instance variable (as done on your side). And close it once you are done with it, by writing rs.close() and rs = null.
Passing table names in a prepared statement is not possible.
The method setString is when you want to pass a variable in a where clause, for example:
select * from clients where name = ?
thx for replies guys,,,
now its working fine.
I noticed sql query cant hold ? to columns too.
So, this sql query to PreparedStatement is working:
String sql = "select * from clients where name like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "a%");
rs = ps.executeQuery();
but, if I try to use column as setString, it doesnt work:
String sql = "select * from clientes where ? like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "name");
ps.setString(2, "a%"):
rs = ps.executeQuery();
Am I correct? or how can I bypass this?
thx again

Categories