where condition is not recognizing my full String - mysql

I am using spring and hibernate in my project. This is My Query. When I execute this query I am getting data from DB. But if I frame the query like this I am getting 0 records.
String fullname1 = "this is my String";
select name,gender from account where fullname='fullname1';
If I create query like this I am getting data. But fullname1 is not a static data.
select name,gender from account where fullname like '%this%';
Problem is if my fullname1 is have only one word then I am getting proper data. If it has multiple words I am not getting data.
Can any one suggest me how to frame query in this situation.

Try to concatenate your string to search like this
select name,gender from account where fullname like '%' + yourVariable + '%';
Assuming yourVariable is containing the string which you want to search.
EDIT:
As confirmed by OP in comments the query which worked for him/her is:
select name,gender from account where fullname='" + fullname1+ "'";
Also your query is prone to SQL Injection. So it is better to use Prepared statement.

Related

Spring data Couchbase #n1ql.fields query

I'm trying to make a N1QL based query on Spring Data Couchbase. The documentation says
#n1ql.fields will be replaced by the list of fields (eg. for a SELECT clause) necessary to reconstruct the entity.
My repository implementation is this one:
#Query("#{#n1ql.fields} WHERE #{#n1ql.filter}")
List<User> findAllByFields(String fields);
And I'm calling this query as follows:
this.userRepository.findAllByFields("SELECT firstName FROM default");
I'm getting this error:
Caused by: org.springframework.data.couchbase.core.CouchbaseQueryExecutionException: Unable to execute query due to the following n1ql errors:
{"msg":"syntax error - at AS","code":3000}
After a little bit of researching, I also tryed:
#Query("SELECT #{#n1ql.fields} FROM #{#n1ql.bucket} WHERE #{#n1ql.filter}")
With this query, I don't get an error, I get all the documents stored but only the ID the other fields are set to null, when my query tries to get the firstName field.
this.userRepository.findAllByFields("firstName");
Anyone knows how to do such a query?
Thank you in advance.
You're misunderstanding the concept, I encourage you to give the documentation more time and see more examples. I'm not sure what exactly you're trying to achieve but I'll throw some examples.
Find all users (with all of their stored data)
#Query("#{#n1ql.selectEntity} WHERE #{#n1ql.filter}")
List<User> findAllUsers();
This will basically generate SELECT meta().id,_cas,* FROM bucket WHERE type='com.example.User'
Notice findAllUsers() does not take any parameters because there are no param placeholders defined in the #Query above.
Find all users where firstName like
#Query("#{#n1ql.selectEntity} WHERE #{#n1ql.filter} AND firstName like $1")
List<User> findByFirstNameLike(String keyword);
This will generate something like the above query but with an extra where condition firstName like
Notice this method takes a keyword because there is a param placeholder defined $1.
Notice in the documentation it says
#{#n1ql.selectEntity} WHERE #{#n1ql.filter} AND test = $1
is equivalent to
SELECT #{#n1ql.fields} FROM #{#n1ql.bucket} WHERE
#{#n1ql.filter} AND test = $1
Now if you don't want to fetch all the data for user(s), you'll need to specify the fields being selected, read following links for more info
How to fetch a field from document using n1ql with spring-data-couchbase
https://docs.spring.io/spring-data/couchbase/docs/2.2.4.RELEASE/reference/html/#_dto_projections
I think you should try below query, that should resolve the issue to get fields based parameter you have sent as arguments.
Please refer blow query.
#Query("SELECT $1 FROM #{#n1q1.bucket} WHERE #{#n1ql.filter}")
List findByFirstName(String fieldName);
Here, bucket name resolve to the User entity and and n1ql.filter would be a default filter.

SQL query to retrieve exactly matching record with or without LIKE

From a rest API URL, I'm receiving a user ID that looks like this: 58988e75c918f5bd5804afd6.
The database has the user name stored in the name field in the format:
58988e75c918f5bd5804afd6 John.
My current SQL query to fetch this record is:
$sql = 'SELECT * FROM users WHERE name LIKE :term';
$result = db_query($sql, array(':term' => db_like($userid)));
$existingUser = $result->fetchObject();
With the current SQL query, even if I supply the partial user ID(58988e75c918f5bd5804), it seems to fetch the John row, which is not something I expect to happen. How to fix the query so that it exactly matches the user ID containing John?
Expected result: No records to be retrieved since the user id did not match exactly.
Update: I fetch the records and then do a substring replace to update the record in the Drupal table.
Note: Feel free to modify the sql query to get the expected result, neednt use LIKE
Use a space in your like term:
Include space in mysql like search
$sql = 'SELECT * FROM users WHERE name LIKE ":term "';
$result = db_query($sql, array(':term' => db_like($userid)));
$existingUser = $result->fetchObject();
Better validate the string size with PHP and then perform mysql like. As you are using same encryption style you will get same number of characters encrypted so.

Sql Query LIKE not working

Hi i have trying to do a query, that receives the value on a querystring, but is not working i think the query it self is no good. could you help me?
So i receive the query on
<%String detalhe = request.getParameter("value");%>
I wont put connections and stuff, because they work with other querys, so the problem are not the connections.
// sql query to retrieve values from the specified table.
String QueryString = "SELECT * FROM ebooko.dadoslivros WHERE Autor LIKE '%"+detalhe+"%'
OR ano LIKE '%"+detalhe+"%'";;
rs = statement.executeQuery(QueryString);
It simply cannot retrive the value, i'm querying.
Adicional info:
Table: dadoslivros
Columns that i need to compare the value: Autor, ano.
for example when i run the Href the value that is passed is: Jules%Verne (i gess it changes SPACES with '%'.
Use URLDecoder#decode() to decode the parameters in the query string.
You should also consider using a PreparedStatement to prevent SQL injection attacks.
I solved it changing the query:
String QueryString = "SELECT * FROM dadoslivros WHERE (Data LIKE '%"+detalhe+"%') OR (Autor LIKE '%"+detalhe+"%')";;
maybe it can help another person ;)

Search returns no rows in mysql query using LIKE and values having "\"

I have some problem regarding the search in mysql.
Below is my query.
SELECT * FROM table WHERE name LIKE "%admin\'s%";
When i am executing this query it will return zero data.
actually i have "admin\'s" stored in db. this "\" is to prevent sql injection. i have used mysql_real_escape_string to prevent the sql injection.
but when i use three times addslashes to my variable it works.
So my below query is working.
SELECT * FROM table WHERE name LIKE "%admin\\\\\\\'s%";
My above query will return the data with name like admin's.
I am not getting where i am wrong.
well for one you shouldnt have data like this in your DB admin\'s .. most likely you double escaped your string ( check if you don't have magic_quotes enabled on your server ).
If you only do
INSERT ... username = "admin\'s";
you will have in your db the username value admin's
so my recomandation would be to go ahead and remove the slashes from your database and then your first query should work.

JDBC prepareStatement doesn't work

I'm trying to use the prepareStatement function. The code is below. After it executes, it returns me a bunch of vlicense strings instead of the values.
When the code finishing the statement.setString(), the statement becomes:
select 'vlicense' from Vehicle
However, it needs to be:
select vlicense from Vehicle
without the quotation marks. Can anyone tell me what's the problem?
statement = oConnection.prepareStatement("select ? from Vehicle");
String tempString = "vlicense";
statement.setString(1, tempString);
resultSet = statement.executeQuery();
You can't use parameter markers for column names, table names, data type names, or basically anything that isn't data.
When you add a bind variable to a statement like this it is escaped, so that actual SQL string in your example would go to the database as "SELECT 'vlicense' FROM Vehicle', selecting a literal string instead of the column name you want.
You need to concatenate that variable column name into your SQL statement before you prepare it:
statement = oConnection.prepareStatement("SELECT " + vlicense + " FROM Vehicle");
Bind variables are really for query parameters as opposed to dynamic queries.
The ? can't be used to specify the fields, just to do some filters in your query like:
statement = conn.prepareStatement("select field from Vehicle where name=?");
In your case your query is built as:
select 'vlicense' from Vehicle
which means: GET ME A STRING 'vlicense' FOR EACH RECORD OF 'Vehicle'. And you'll get n repeated strings depending on the number of records in your table
It has nothing to do with jdbc, prepared-statements or mysql.
It's just a wrong sql statement.
If you type:
Select 'justanexample' from Vehicle
and the table contains 4 lines, you will get 4 times
'justanexample'
'justanexample'
'justanexample'
'justanexample'
as result.
You did not specify your the table structure, but I guess the
statement should somehow look like this:
select * from Vehicle where license = ?