I want to check if given text contains in a sub string present in db,
ex:- string to search - "my name is john"
string in db/column_name- "john".
SQL query
select * from `demo` where instr('my name is john','column_name') > 0
What is the Django Equivalent of above query?
NOTE - The actual string is very large about 255 characters so I can't use regex to extract string as the input will be dynamic.
You would first use annotate to annotate your string to the query and then use the contains lookup [Django docs] on it to find if it contains the given column:
from django.db.models import CharField, F, Q, Value
queryset = TestModel.objects.annotate(
search_text=Value('my name is john', output_field=CharField())
).filter(
Q(search_text__contains=F('column_name')) & Q(search_text__contains=F('second_column_name'))
)
class YourModel(models):
message = models.CharField(max_length=255)
if you want to query for message substring try like this:
YourModel.objects.filter(message__contains='john')
in return you will get list of objects/db rows where the column (message) has a substirng of 'john'
Related
Here is my string column with value for ex:
Customer: check, ID: 3963f4bb-59fb-4a26, NAME: TAMIL
I want only the value of "3963f4bb-59fb-4a26" which is in between start of "ID: "
and end keyword of ", ".
Please anyone suggest how to extract only that ID value.
The length of string may not be same and values inside may in mixed format also, so based on ID I wants to extract that string.
I tried using substring, but not able to extract result.
You can do it using SUBSTRING_INDEX :
select description, SUBSTRING_INDEX(SUBSTRING_INDEX(description, 'ID:', -1), ',', 1) as snippet
from my_table;
Check it here : https://dbfiddle.uk/K5FNq-EY
I am new to python and currently learning to use SQL with python. I have the following code:
word = input("Enter a word: ")
query = cursor.execute("SELECT * FROM Dictionary WHERE Expression LIKE '%s%' " % word)
results = cursor.fetchall()
The second line throws an error since I don't think I can use '%s%' like that? How would I change this so as to be able to make this work? I want to be able to return all related entries to the users input. So if the user inputs "rain", then I want the query to return all possible results e.g. "raining", "rainy" etc. Thank you.
You can try
query = cursor.execute(f"SELECT * FROM Dictionary WHERE Expression LIKE '%{word}%' ")
You should use cursor.execute() parameter substitution rather than string formatting, to prevent SQL injection.
Then use CONCAT() to surround the search string with %.
query = cursor.execute("SELECT * FROM Dictionary WHERE Expression LIKE CONCAT('%', %s, '%' "), (word,))
My query is:
result = connection.execute(
"select id_number from Table where string like '_stringStart%' limit 1;")
gives the error:
query = query % escaped_args
TypeError: not enough arguments for format string
A quick google said to use %% instead of % but that doesn't work either. How do I escape the % or is there another way to query for a string that starts with a random letter then a certain sequence?
Since this is a literal string, you're better off using a bound parameter here (illustrated using text()):
from sqlalchemy import text
connection.execute(
text("select * from table where "
"string like :string limit 1"),
string="_stringStart%")
Another way to implement bound parameters:
from sqlalchemy import text
connection.execute(
text("select id_number from Table where string like :string limit 1").\
bindparams(string="_stringStart%")
)
or even typed strictly:
from sqlalchemy import bindparam, String, text
connection.execute(
text("select id_number from Table where string like :string limit 1").\
bindparams(bindparam("string", type_=String)),
{"string"="_stringStart%"}
)
Bear in mind that text() construct is deprecated sine SQLAlchemy 1.4 and will be removed in SQLAlchemy 2.0.
I Need help for fetch records from table using Go.
My Problem is that i'm writing MySQL query and add another where clause i.e HPhone number, Here HPhone number inserted in data base with format like 999-999-9999.And i passed this HPhone Number in format like 9999999999. which is not matching with correct data base field value. And i used SUBSTRING for add hyphen between numbers but it does not get records but when i passed like 999-999-9999 without SUBSTRING it return records.
Here i demonstrate how i used this.
strQry = `SELECT * from table WHERE Depot = ?`
if HPhone != "" {
strQry += ` AND HPhone = ?`
}
queryArgs := []interface{}{RouteAvailability.Depot}
if HPhone != "" {
queryArgs = append(queryArgs, "SUBSTRING("+HPhone+",1,3)"+"-"+"SUBSTRING("+HPhone+",4,3)"+"-"+"SUBSTRING("+HPhone+",7,4)")
}
Help would be appreciated.
Thanks in advance.
Instead of SUBSTRING you can use REPLACE like so:
queryArgs := []interface{}{RouteAvailability.Depot}
if HPhone != "" {
strQry += ` AND REPLACE(HPhone, '-', '') = ?`
queryArgs = append(queryArgs, HPhone)
}
If possible I would suggest you normalize your data, i.e. decide on a canonical format for a particular data type and everytime your program receives some input that contains that data type you format it into its canonical form, that way you can avoid having to deal with SUBSTRING, or REPLACE, or multiple inconsistent formats etc.
This won't work as you are using prepared statements, and the argument you are building when HPhone is not empty will be used in escaped form - so when executing the query, it won't compare the HPhone values with the computed result of some substring, but with a string containing SUBSTRING(9999...
Very similar to this question MySQL Dynamic Query Statement in Python
However what I am looking to do instead of two lists is to use a dictionary
Let's say i have this dictionary
instance_insert = {
# sql column variable value
'instance_id' : 'instnace.id',
'customer_id' : 'customer.id',
'os' : 'instance.platform',
}
And I want to populate a mysql database with an insert statement using sql column as the sql column name and the variable name as the variable that will hold the value that is to be inserted into the mysql table.
Kind of lost because I don't understand exactly what this statement does, but was pulled from the question that I posted where he was using two lists to do what he wanted.
sql = "INSERT INTO instance_info_test VALUES (%s);" % ', '.join('?' for _ in instance_insert)
cur.execute (sql, instance_insert)
Also I would like it to be dynamic in the sense that I can add/remove columns to the dictionary
Before you post, you might want to try searching for something more specific to your question. For instance, when I Googled "python mysqldb insert dictionary", I found a good answer on the first page, at http://mail.python.org/pipermail/tutor/2010-December/080701.html. Relevant part:
Here's what I came up with when I tried to make a generalized version
of the above:
def add_row(cursor, tablename, rowdict):
# XXX tablename not sanitized
# XXX test for allowed keys is case-sensitive
# filter out keys that are not column names
cursor.execute("describe %s" % tablename)
allowed_keys = set(row[0] for row in cursor.fetchall())
keys = allowed_keys.intersection(rowdict)
if len(rowdict) > len(keys):
unknown_keys = set(rowdict) - allowed_keys
print >> sys.stderr, "skipping keys:", ", ".join(unknown_keys)
columns = ", ".join(keys)
values_template = ", ".join(["%s"] * len(keys))
sql = "insert into %s (%s) values (%s)" % (
tablename, columns, values_template)
values = tuple(rowdict[key] for key in keys)
cursor.execute(sql, values)
filename = ...
tablename = ...
db = MySQLdb.connect(...)
cursor = db.cursor()
with open(filename) as instream:
row = json.load(instream)
add_row(cursor, tablename, row)
Peter
If you know your inputs will always be valid (table name is valid, columns are present in the table), and you're not importing from a JSON file as the example is, you can simplify this function. But it'll accomplish what you want to accomplish. While it may initially seem like DictCursor would be helpful, it looks like DictCursor is useful for returning a dictionary of values, but it can't execute from a dict.