SQL fuzzy search - java

I have to call SQL database search in my Java program.
The retrieving condition is that user input string partially matches NAME filed and not case sensitive. For example, if user input "joe", students' records with name like "Joea", "Bjoe","JOEED" should be returned.
While I tried to write code as bellow. It doesn't seem to be able to work out.
Can someone tell me why? Thanks.
String fuzzySearch = "UPPER(%" + inputStr + "%)";
String query = "SELECT * FROM student WHERE UPPER(student.name) LIKE ? ";
PreparedStatement prepStatement = con.prepareStatement(query.toString());
prepStatement.setObject(1,fuzzySearch);

As you are using a string bind variable, you are saying
WHERE UPPER(student.name) LIKE 'UPPER(%joe%)'
instead of
WHERE UPPER(student.name) LIKE UPPER('%joe%')
So use
String fuzzySearch = "%" + inputStr + "%";
String query = "SELECT * FROM student WHERE UPPER(student.name) LIKE UPPER(?) ";
PreparedStatement prepStatement = con.prepareStatement(query.toString());
prepStatement.setObject(1,fuzzySearch);
instead.

Related

Imported String from Database has quotes("), want to use String to Query Database again

So I have a script that retrieves a list of items that were used on a product within a time period. Our database is 'jerry-rigged', so to say, where we do not have these items listed as their code, but by a description. I can run this description through another table on our database to retrieve an item code, but I run into an issue with items that have a double quote in them, like '2" Self Tapping Screw', where the double quotes causes an issue with my query. Below are the issue lines I have:
String description = resultSet.getString(1); //description = "2" Self Tapping Screw
String sql = "Select itemcode from database.table where description "
+ "= \"" + description + "\";
How can I replace these double quotes with the regex character? I tried
description = description.replace("\"","\\"");
but I do not think I am getting it right, because it just changes every '"' to "\".
Use PreparedStatement:
Connection conn = DriverManager.getConnection("<Your connection string>");
String sql = "Select itemcode from database.table where description = ?";
PreparedStatement prep = con.prepareStatement(sql);
prep.setString(1, resultSet.getString(1));
prep.executeUpdate();
This is much safer than trying to escape Strings by yourself.

Hibernate query to search for a particular sub string in a string field

I have a field in one of my tables that has a field to store urls and the POJO for that table is as follows:
public class ContentDefinition
{
private String contentName;
private int contentId;
private String contentType;
private String contentUrl;
}
I am trying to write a query to check if the contentUrl field contains url that ends with the string address-book.
I am using the following query:
String hql = " from ContentDefinition WHERE contentUrl LIKE '%'address-book'%'";
Query query = getCurrentSession().createQuery(hql);
List<ContentDefinition> resultsList = query.list();
but I am getting an exception:
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: address near line 1, column 130
Is there any solution, my url can be anything, but always ends with /address-book
String hql = " from ContentDefinition WHERE contentUrl LIKE :addressBook ";
Query query = getCurrentSession().createQuery(hql);
query.setParameter("addressBook","address-book");
List<ContentDefinition> resultsList = query.list();
String hql = " from ContentDefinition WHERE contentUrl LIKE '%address-book%' ";
Change above line. Rest of code looks good. I have tested a similar code.
Read upon chapter SQL LIKE Operator.
The doc says:
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
where animalType like '%cats%'
Which means, you should change your query from:
String hql = " from ContentDefinition WHERE contentUrl LIKE '%'address-book'%'";
to
String hql = " from ContentDefinition WHERE contentUrl LIKE '%address-book%'";

How to display a student's record (only who logged in) in java connected with database?

i write this code to connect java with database, and i have a login pahe where i entered username and that should display the record of the student who logged in for that i have executed this query
String query= "select * from Student where Name = '" + new Login().equals(jTextField1.getText()) + "'";
but it's not working .
Your query compares name with new Login().equals(jTextField1.getText()) i.e. which runs equals method which would either return true or false.
Also you are trying to compare login object with String which compiler wont be happy with.
You should change your line from:
String query ="select * from Student where Name = '" +new Login().equals(jTextField1.getText()) +"'" ;
To:
String query ="select * from Student where Name = '" + jTextField1.getText() +"'" ;
Note - Your SQL is vulnerable to SQL injection, better use prepared statement and provide input like username say via map.

MySql Prepared Statement to check particular table JAVA

I wonder if there is a way to select table with user input in the following statement:
myStmt = db.myConn.prepareStatement("select * from Rooms where "
+ "idRooms = ?");
myStmt.setInt(1, roomNum);
myRs = myStmt.executeQuery();
Is there a possibility to do something like select * from =? where idRooms = ? to select Rooms with prepared statement upon user input?
myStmt.setString(1, Room);
mysStmt.setInt(2, roomID);
Thanks
It is not possible to add a table name as a parameter.
You can simply create a string containing your constructed query as follows:
String query = "select * from " + userParamVariable + " where idRooms = ?"
I guess you manage your tables with splitting, but unfortunately PreparedStatement does not support it, you can manually replace the table name with String.format() method.

Relation "table name" doesn't exist postgresql

Hi I'm doing a query in java, i have java and posgres connected with the driver 9.3-1102-jdbc41
This is my query: query = "SELECT * FROM" +"\"users\" "+ " where user="+"'"+name+"'"+"and pass =" +"'"+pass+"'";
when I run it, this error appears:
Relation "users name" doesn't exist
Here and in others sites a possible solution is checking the quotes or the capital letters.
But I´m sure about the capital letters and this is what I tried:
query = "SELECT * FROM" +"\"users\" "+ " where user="+"'"+name+"'"+"and pass =" +"'"+pass+"'";
query = "SELECT * FROM users where user="+"'"+name+"'"+"and pass =" +"'"+pass+"'";
query = "SELECT * FROM" +"\"sysmar.users\" "+ " where user="+"'"+name+"'"+"and pass =" +"'"+pass+"'";
Error relation users does not exist
"SELECT * FROM users where user="+name+"and pass =" +pass;
syntax error near to pass
Thanks in advance for your answers and time
try:
"SELECT * FROM users where \"user\" ='"+name+"'and pass ='" +pass+"'";
But it's harmful for sql injection. See PreparedStatements.
For PostgreSQL you shouldn't need to put quotes around the table name unless it's a reserved keyword. Users isn't a keyword, but user just so happens to be one of them.
Your query is hard enough to read with the extra concatenation operations and spacing issues. Perhaps there is a syntax error and you just need to clean it up:
q = "SELECT * FROM users WHERE \"user\" = '" + name + "' AND pass = '" + pass + "'";
You want the final evaluated string to look like (for example):
SELECT * FROM users WHERE "user" = 'cory' AND pass = '12345';
But as others have mentioned, you should also switch to using prepared statements. This code is probably vulnerable to SQL injection attacks.
You really shouldn't concatenate variables with SQL queries, you are becoming vulnerable to SQL injection then. You better be using Prepared Statements which will allow you to write queries in more readable and secure fashion.
Connection conn = DriverManager.getConnection(...);
String queryString = "SELECT * FROM users WHERE user = ? AND pass = ?";
PreparedStatement query = conn.prepareStatement(queryString);
query.setString(1, name);
query.setString(2, password);
ResultSet result = query.executeQuery();

Categories