JDBC ilike query java - java

JDBC successfully connected to PostgreSQL. But some ilike query still have problems. only 1 code is working. I want the first and the third one to working properly.
--------------- not working
String ilikequery = "SELECT * FROM emp where ? iLIKE '%C%' ";
PreparedStatement ilikestatement = Main.connection.prepareStatement(ilikequery);
ilikestatement.setString(1,"name");
ResultSet resultSet = ilikestatement.executeQuery();
-------------- this one working,
String queryname = "Cowen";
String query = "select * from emp where name = ?";
PreparedStatement statement = Main.connection.prepareStatement(query);
statement.setString(1,queryname);
ResultSet resultSet = statement.executeQuery();
------------this one not working.
String ilikequerywithparameter = "SELECT * FROM emp" + " where name iLIKE '%"+"?"+"%' ";
PreparedStatement ilikestatementpara = Main.connection.prepareStatement(ilikequerywithparameter);
ilikestatementpara.setString(1,"c");
ResultSet resultSet = ilikestatementpara.executeQuery();
The last code snippet have Exception error.Exception in thread "main" org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns:
-------- this one is working.
String simpleilikequery = "SELECT * FROM emp" + " WHERE name iLIKE '%C%'";
PreparedStatement simpleilikestatement = Main.connection.prepareStatement(simpleilikequery);
ResultSet resultSet = simpleilikestatement.executeQuery();

You need to pass the wildcards as part of the parameter, not the prepared statement:
String sql = "SELECT * FROM emp where name iLIKE ?";
PreparedStatement stmt = Main.connection.prepareStatement(ilikequerywithparameter);
stmt.setString(1,"%c%");
Or alternatively use concat() in the SQL string if you don't want to (or can't) modify the parameter itself.
String sql = "SELECT * FROM emp where name iLIKE concat('%', ?, '%')";
PreparedStatement stmt = Main.connection.prepareStatement(ilikequerywithparameter);
stmt.setString(1,"c");

Related

What's wrong with this SQL command?

I have a problem with a SQL Command.
I have a string that holds a SQL command, but when I run, it returns me an error: Column n1 does not exist Note: n1 is what I typed in my textField.
Code:
String nameprod tf_NameProd.getText = ();
         String sql = "select * from Product where prod_name =" + nameprod;//<-- this is my query
         iaeprod.Table(sql, tbl_Prod);
Any idea where I am missing?
You need to put single quotes around the string in your SQL. For example in your case it should be
"select * from Product where prod_name = '" + nameprod + "'";
String sql = "select * from Product where prod_name = '" + nameprod + "'";
because prod_name is a String use single quotes around the value
String sql = "select * from Product where prod_name ='" + nameprod+"'";
it will better to use prepared statement
Use this method instead:
Connection dbConnection = getDBConnection();
PreparedStatement stmt = null;
String nameProd = "select * from Product where prod_name = ?";
stmt = connection.prepareStatement(nameProd);
stmt.setString(1, tf_NameProd.getText() );
ResultSet rs = stmt.executeQuery();
P.S.: I haven't compiled this code. Please put try and catch statements at appropriate places

Trying to join 2 tables in java but i get a Error

Im working with Sql and java.
This works in sql:
use mybank
Select * from Account
inner join CustomerAccount on accountid = id
where customerid = 18
In java i write this:
String sql = ("Select * From Account inner join CustomerAccount on accountid = id where customerid =?;");
try (Connection con = myDbManager.getConnection())
{
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, customer.getId());
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
customer.getId gives me 18.
but i get this error;
Incorrect syntax near '?'.
The problem is here:
ResultSet rs = st.executeQuery(sql);
You're using Statement#executeQuery(String sql) which is inherited from Statement interface. You should use PreparedStatement#executeQuery.
In short, change that line to:
ResultSet rs = ps.executeQuery();
^ parameter-less
And remove this Statement variable from your code, it will just confuse you and future readers of the code:
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, customer.getId());
//Statement st = con.createStatement();
^ this generates confusion
Also, you should remove the semicolon in your SQL statement when executing it form Java:
String sql = "Select *"
+ " From Account"
+ " inner join CustomerAccount"
+ " on accountid = id"
+ " where customerid = ?";
SQL-Queries in Java don't use the ';':
String sql =( "Select * From Account inner join CustomerAccount on accountid = id where customerid =?");

Use the value of a combo box in a SQL query

How can I use the value of a combo box in a SQL query with Java?
I try this code but it doesn't work.
String sql = " select * from table1 where ? like ?";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, (String) jComboBox2.getSelectedItem());
pst.setString(2, txtsearch.getText() + "%");
rs = pst.executeQuery();}
If I use this code, it works.
String sql = " select * from table1 where Name like ?";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txtsearch.getText() + "%");
rs = pst.executeQuery();}
Well, you can do something like this:
try {
String sql = "select * from table1 where ";
sql += (String) jComboBox2.getSelectedItem();
sql += " like ";
sql += txtsearch.getText() + "%";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
}
The place holder (?) is actually designed for the column values not for column/table name. Make use of string concatenation:
String sql = "select * from table1 where "
+ jComboBox2.getSelectedItem()
+" like ?";

How to work with subselects in combination with PreparedStatements?

For example I have the following SQL Code:
SELECT *
FROM customer c
WHERE 2 = (SELECT count(*)
FROM account a
WHERE a.cust_id = c.cust_id);
How can I transform that SQL statement to a prepared statement command?
String queryString = " SELECT * FROM customer c";
queryString += " WHERE ? = (SELECT count(*) FROM account a WHERE a.cust_id = c.cust_id)";
PreparedStatement stmt = connection.prepareStatement(queryString);
stmt.setInt(1, theCountYouLookFor) // theCountYouLookFor would be 2 in your example

Oracle JDBC select with WHERE return 0

Similar question to:
Strange problem with JDBC, select returns null
but people didn't ask for this.
My code:
public int myMethod(String day) throws SQLException{
String sql = "Select count(*) from MyTable WHERE someColumn = " + day;
Connection connection = ConnFactory.get();
PreparedStatement prepareStatement = null;
ResultSet resultSet = null;
int ret = -1;
try{
prepareStatement = connection.prepareStatement(sql);
resultSet = prepareStatement.executeQuery(sql);
if(resultSet.next()){
ret = resultSet.getInt(1);
}
}
catch(SQLException sqle){
// closing statement & ResultSet, log and throw exception
}
finally{
// closing statement & ResultSet
}
ConnFactory.kill(connection);
return ret;
}
This code always return 0. I try to log sql before execution and try to run it in SQLdeveloper and get correct value (over 100).
When I remove WHERE, sql = "Select count(*) from MyTable query return number of all rows in table.
I use Oracle 10g with ojdbc-14.jar (last version from maven repo) and Java 6.
day has not been quoted correctly, I would suggest using a prepared statement like a prepared statement as follows:
...
try {
prepareStatement = connection.prepareStatement("Select count(*) from MyTable WHERE someColumn = ?");
prepareStatement.setString(1,day);
...
is the same as:
sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";
with several advantages over the latter (mainly security and performance). See:
http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html
First of all using sql like this is not advisable. Because it leads to SQL injection.
In the future try using like below and use PreparedStatement to execute
String sql = "Select count(*) from MyTable WHERE someColumn = ? "
For your solution did you try
String sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";
karim79 is good answer, you forgot add apostrophe signs in your "day" value
String sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";

Categories