ValueError("unsupported format character 'A' (0x41) at index 185",) - mysql

I am trying to execute a query which lists certain values of my db that match the inputs of my html search form. I want it to do the search even if some of the form inputs are empty inputs.I am using Python 3.4 and my query is something like this:
query=("select DISTINCT val1,val2,val3,val4 from tab1,tab2 WHERE tab1.val1=tab2.val1 AND onoma LIKE '%' AND epitheto LIKE '%' AND (val4 between % AND %)" )
data =(d1, d2, d3 ,d4)
c.execute("SET NAMES utf8")
c.execute(query,data)
the error I get is this:
ValueError("unsupported format character 'A' (0x41) at index 185",)
Please, if you know how i can fix this, i would really appreciate it. I'm a begginer with databases.
Thanks in advance

Placeholders for parameters are spelled %s, not %:
query = """
select DISTINCT val1,val2,val3,val4 from tab1,tab2
WHERE tab1.val1=tab2.val1 AND onoma LIKE %s AND
epitheto LIKE %s AND
(val4 between %s AND %s)
"""
data = ('%{}%'.format(d1), '%{}%'.format(d2), d3 ,d4)
c.execute(query, data)
Note that you should not add quotes around placeholders (leave those to the database driver), and for a LIKE query, you need to add the wildcards to the parameter value. I used str.format() here to put % wildcards before and after each value. A LIKE query without wildcards (so % or _) may as well just use = equality tests.

Related

MySQL full text search on JSON data

I'm trying to replicate the following LIKE query using a full text search on JSON data;
SELECT * FROM table
WHERE response LIKE '%"prod_id": "foo"%'
AND response LIKE '%"start_date": "2016-07-13"%'
In my database the above query returns 28 rows
This is my attempt:
SELECT * FROM table
WHERE MATCH(response)
AGAINST('+"\"prod_id\": \"foo\"",+"\"start_date\": \"2016-07-13\""')
However this returns over 4,500 rows (the same as running the first query for only the prod_id ~1,900 rows when running the first query on just the date)
It was my understanding that +"text here" would indicate a required word, and that literal double quotes (present in the JSON data) should be escaped, and that , would indicate a split between the two strings I'm looking for. What am I not understanding correctly? Is there any point in running this as a full text query anyway?
Thanks to #Sevle I've tweaked my query like so, and it's returning the correct results;
SELECT * FROM table
WHERE MATCH(response)
AGAINST('+\"prod_id: foo\" +\"start_date: 2016-07-13\"' IN BOOLEAN MODE)
The comma was not helping and I was escaping the wrong characters, and of course I did need IN BOOLEAN MODE to be added. Finally, I removed the double quotes I was searching for in the JSON string.
It may also be worth noting that as I'm using PHP PDO to run this query I also had to make the following tweaks.
Instead of constructing the query like so trying to bind the variables like I normally would;
$query = $db->prepare('...AGAINST('+\"prod_id: :prod_id\" +\"start_date: :start_date\"');
$query->execute(array('prod_id' => 'foo', 'start_date' => '2016-07-13'));
I had to do this, as I found I could not bind variables in full text searches
$sql_against = $db->quote('...AGAINST('+\"prod_id: foo\" +\"start_date: 2016-07-13\"');
$query = $db->prepare("...AGAINST($sql_against IN BOOLEAN MODE)")

LIKE MySQL search not functioning with CONCAT

I got a problem regarding SQL query. If single word SQL query can detect the string, but if I add multiple words inside the string, it won't show any results.
SELECT * FROM rules WHERE keyword LIKE CONCAT('%','$message','%')
Input 1 (show results)
$message = "ASK"
Input 2 (show no results)
$message = "I WANT TO ASK"
I'm assuming you want those rows where the value of the keyword column is part of the message. That's the typical use case for key words.
If that's right then you've get this result with the help of the function INSTR:
SELECT * FROM rules WHERE INSTR('$message', keyword) > 0;
While
SELECT * FROM rules WHERE '$message' LIKE CONCAT('%', keyword, '%');
would work most times too, it's got the restriction that the keyword musn't contain the wildcard characters for the LIKE operator: % and _. INSTR doesn't have this restriction.

How do I use WHERE LIKE properly in a mysql prepared statement?

I'm trying to puzzle out how to add a LIKE to this prepared statement.
SELECT convention_name FROM events_master
WHERE (convention_name = ?);
The goal is to see if the convention name is similar to something that already exists in convention_name. I do understand that it checks for an exact match already.
Thanks in advance.
SELECT convention_name FROM events_master
WHERE (convention_name LIKE 'partofname' + '%');
The % character is a wild char so if you put it in the back it will search for anything that begins with 'partofname' + blah appended to it.
if it's Like = '%partofname%' then partofname could have characters before or after it.
If SQL LIKE clause is used along with % characters, then it will work
like a meta character (*) in UNIX while listing out all the files or
directories at command prompt.
Without a % character, LIKE clause is very similar to equals sign
along with WHERE clause.
$sql = $dbh->prepare(SELECT convention_name FROM events_master
WHERE convention_name LIKE ?");
$sql->execute(array('%'.$yourSearchString.'%'));
For example:
String query = "SELECT convention_name FROM events_master WHERE convention_name like ?";
PreparedStatement stm = conn.prepareStatement(query);
stm.setString(1, "%car%");
Your argument may contain wildchar %, then it will find for example card, scart ..
If this substring match is not enough, then you can use soundex algorithm to find similar strings. See how to compute similarity between two strings in MYSQL for more options.

How can i separate the data from selected data

I have a column in my table name as URL and it contains Multiple value like "https://www.google.com/#q=how+to+make+a+android+app"
and
http://www.bing.com/search?q=how+to+make+a+android+app&go=&qs=n&form=QBLH&pq=how+to+make+a+android+app&sc=8-15&sp=-1&sk=
I want to get data separately in output like
website = https://www.google.com
Keyword = how to make a android app.
Any Idea Plz, How can i get this in MySql.
you can use substr() function in php to cut string. In your case, you can get the characters up to the end of 'https://www.google.com'.
read more at http://ro1.php.net/substr
in case you want to do it directly in your query, you can use substr() as well. Sql syntax goes like this:
SELECT SUBSTR(column, start_position, desired_length) FROM table_name
*SELECT SUBSTR(column_name, 1, 20) FROM table_name;*

mysql: replace \ (backslash) in strings

I am having the following problem:
I have a table T which has a column Name with names. The names have the following structure:
A\\B\C
You can create on yourself like this:
create table T ( Name varchar(10));
insert into T values ('A\\\\B\\C');
select * from T;
Now if I do this:
select Name from T where Name = 'A\\B\C';
That doesn't work, I need to escape the \ (backslash):
select Name from T where Name = 'A\\\\B\\C';
Fine.
But how do I do this automatically to a string Name?
Something like the following won't do it:
select replace('A\\B\C', '\\', '\\\\');
I get: A\\\BC
Any suggestions?
Many thanks in advance.
You have to use "verbatim string".After using that string your Replace function will
look like this
Replace(#"\", #"\\")
I hope it will help for you.
The literal A\\B\C must be coded as A\\\\A\\C, and the parameters of replace() need escaping too:
select 'A\\\\B\\C', replace('A\\\\B\\C', '\\', '\\\\');
output (see this running on SQLFiddle):
A\\B\C A\\\\B\\C
So there is little point in using replace. These two statements are equivalent:
select Name from T where Name = replace('A\\\\B\\C', '\\', '\\\\');
select Name from T where Name = 'A\\\\B\\C';
Usage of regular expression will solve your problem.
This below query will solve the given example.
1) S\\D\B
select * from T where Name REGEXP '[A-Z]\\\\\\\\[A-Z]\\\\[A-Z]$';
if incase the given example might have more then one char
2) D\\B\ACCC
select * from T where Name REGEXP '[A-Z]{1,5}\\\\\\\\[A-Z]{1,5}\\\\[A-Z]{1,5}$';
note: i have used 5 as the max occurrence of char considering the field size is 10 as its mentioned in the create table query.
We can still generalize it.If this still has not met your expectation feel free to ask for my help.
You're confusing what's IN the database with how you represent that data in SQL statements. When a string in the database contains a special character like \, you have to type \\ to represent that character, because \ is a special character in SQL syntax. You have to do this in INSERT statements, but you also have to do it in the parameters to the REPLACE function. There are never actually any double slashes in the data, they're just part of the UI.
Why do you think you need to double the slashes in the SQL expression? If you're typing queries, you should just double the slashes in your command line. If you're generating the query in a programming language, the best solution is to use prepared statements; the API will take care of proper encoding (prepared statements usually use a binary interface, which deals with the raw data). If, for some reason, you need to perform queries by constructing strings, the language should hopefully provide a function to escape the string. For instance, in PHP you would use mysqli_real_escape_string.
But you can't do it by SQL itself -- if you try to feed the non-escaped string to SQL, data is lost and it can't reconstruct it.
You could use LIKE:
SELECT NAME FROM T WHERE NAME LIKE '%\\\\%';
Not exactly sure by what you mean but, this should work.
select replace('A\\B\C', '\', '\\');
It's basically going to replace \ whereever encountered with \\ :)
Is this what you wanted?