Problem Using Cursor to Execute a Database Query - python

I'm trying to do a query similar to this:
ctx = snowflake.connector.connect(
host=host,
user=user,
password=password,
account=account,
warehouse=warehouse,
database=database,
schema=schema,
protocol='https',
port=port)
## Create a cursor object.
cur = ctx.cursor()
## Execute a statement that will generate a result set.
sql = "select * from t"
cur.execute(sql)
My query looks something like this:
select NUMBER, ID, DATE, CODE from DATABASE.SCHEMA.TABLE
where (cast(CODE as string) like 'ABC12%'
and (DATE < '2021-12-31' and DATE >= '2021-10-01')
I'm getting this error:
ProgrammingError: 001003 (42000): SQL compilation error:
syntax error line 3 at position 52 unexpected '<EOF>'.
I've looked up this error code and tried removing any special characters that might be there, but no luck.
Thanks in advance

If we re-format the SQL:
select
NUMBER,
ID,
DATE,
CODE
from DATABASE.SCHEMA.TABLE
where (
cast(CODE as string) like 'ABC12%'
and (
DATE < '2021-12-31' and DATE >= '2021-10-01'
)
we can see you are missing the close bracket/paren to the WHERE clause.
But you don't actually need any brackets on this:
select
NUMBER,
ID,
DATE,
CODE
from DATABASE.SCHEMA.TABLE
where CODE::text like 'ABC12%'
and DATE < '2021-12-31' and DATE >= '2021-10-01'

Related

can we take user input using python for mysql table values?

I tried taking input,but its showing error.
raise errors.ProgrammingError(
ProgrammingError: Not all parameters were used in the SQL statement
A part of code that i tried,
`#D_O_B
import datetime
year = int(input('Enter birth year'))
month = int(input('Enter birth month'))
day = int(input('Enter birth day'))
D_O_B = datetime.date(year, month, day)
#Age
A=int(input("Enter age"))
sql = """INSERT INTO PLAYER_DETAILS(
Name,DATE_OF_BIRTH ,Age ,Federation ,Elo_RATING ,Title)
VALUES ( %s,%d ,(%d %b %y), %s,%d , %s)"""
val = (N,D_O_B,A,Fed,RATING,T)
cursor.execute(sql, val)
db.commit()
pip install pyodbc
pyodbc is open source odbc driver for python will allow you to connect sql,
Connect with
import pyodbc
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')
then Create Cursor
cursor = cnxn.cursor()
and then create query like you do in sql query and wherever you want to use user input , replace it with ? add second argument of execute as array and in array put respective values
cursor.execute("""
select user_id, user_name
from users
where last_logon < ?
and bill_overdue = ?
""", [datetime.date(2001, 1, 1), 'y'])
you can pass multiple argument if you dont want to use array as second argument but it also should be respective
cursor.execute("insert into products(id, name) values (?, ?)", 'pyodbc', 'awesome library')
and do commit after insert update or delete
cnxn.commit()
you found more here in official docs Getting Started

Passing variables into a MySQL query using python

I have a database with some records that have a date field of "05221999". I am trying to do a SQL query from the input of the user based on just the month and year. In this case I am interested in all the records with the month of 05 and the year of 1999.
Unfortunately, I can't get the Python/SQL syntax correct. Here is my code so far:
def submitact(self):
date = self.md.get()
month = date[0:2]
year = date[2:7]
db = pymysql.connect("localhost", "username", "password", "database")
cursor = db.cursor()
cursor.execute("SELECT * FROM `table` WHERE `Code` = 'RM' AND `Date` LIKE %s'_'%s", (month, year))
results = cursor.fetchall()
print(results)
cursor.close()
db.close()
I've done several variations on the SELECT statement and they either return errors or nothing.
Thanks!
In the code snippet below, I used f-string style to format the query string
[...]
query = f"SELECT * FROM `table` WHERE `Code` = 'RM' AND LEFT(`Date`, 2) = '{month}' AND RIGHT(`Date`, 4) = '{year}'"
cursor.execute(query)
[...]
try with this:
query = "SELECT * 'table' WHERE 'Code' = 'RM' AND 'Date' LIKE '%{0}_{1}'".format(month, year)
cursor.execute(query)
In this way, 'query' variable value will be:
"SELECT * FROM 'table' WHERE 'Code' = 'RM' AND 'Date' LIKE '%05_1999'"
For more information about string formatting, let's have a look to Python String Formatting Best Practices - Real Python

Why I got an error when I want to count the frequency of data for multiple table in mysql? Flask is used to create web app

I want to create a dashboard widget in my web app. The first step is to count the frequency of pos, neg and neu in mysql from two table. I tried to find the solution in Flask, but not many. Hope u can help me.
The error that I got is:
MySQLdb._exceptions.OperationalError: (1241, 'Operand should contain 1 column(s)')
Table in mysql:
ques9
ques10
My code:
#app.route('/we/<string:programid>')
def we(programid):
# Create cursor
cur = mysql.connection.cursor()
result = """SELECT(
(SELECT programid,sentiment, COUNT(*)
FROM ques9 AS question9
WHERE programid= %s
GROUP BY sentiment),
(SELECT programid,q10_sentiment, COUNT(*)
FROM ques10 AS question10
WHERE programid=%s
GROUP BY q10_sentiment ))"""
data_tuple = (programid, programid)
cur.execute(result, data_tuple)
program = cur.fetchall()
mysql.connection.commit()
if result > 0:
return render_template('we.html',program=program)
else:
msg = 'No Results Found'
return render_template('we.html', msg=msg)
# Close connection
cur.close()
The group by has to be after the where clause
So i posted all the python code, i thought about adding a try, but that you can look up
Your sql has some problems like the group an his own,l but your python code has also flaws, as you can see below. The variables for sql query and the data to send, i out there so that it looks somewhat cleanber
connection = mysql.connector.connect(host='localhost',
database='test_db',
user='user',
password='password')
cur = connection.cursor(prepared=True)
sql_update_query = """SELECT(
(SELECT programid,sentiment, COUNT(*)
FROM ques9 AS question9
WHERE programid= %s
GROUP BY sentiment),
(SELECT programid,q10_sentiment, COUNT(*)
FROM ques10 AS question10
WHERE programid=%s
GROUP BY q10_sentiment ))"""
data_tuple = (programid, programid)
cur .execute(sql_update_query, data_tuple)
connection.commit()
if (connection.is_connected()):
cur.close()
connection.close()

Dynamic query in django with "|" character in WHERE clause and variable in tablename

I have a dynamic sql query running in my views.py and have already ran others that work fine. I am not worried about sql injections because this is a private website. However, the parameters in my And clause has the character "|" in it which throws the error:
Unknown column "X" in 'where clause'
I have looked at solutions but they all use non dynamic query which then prohibits me from making the tablename a variable.
Here is what I want:
mycursor = mydb.cursor()
assembly_name = "peptides_proteins_000005"
group_id = 5
protein_id = "sp|P48740|MASP1_HUMAN"
qry = "SELECT * FROM %s WHERE group_id = %i AND protein_id = %s" % (assembly_name, group_id, protein_id)
mycursor.execute(qry)
But this throws the error:
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'sp' in 'where clause'
When I try doing following the answers of similar questions I get this:
qry = "SELECT * FROM %s WHERE group_id = %i AND protein_id = %s"
mycursor.exectue(qry, (assembly_name, group_id, protein_id))
However, I still get this error:
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
Changing the %i to a %s fixes the error above but then I get a new error:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''peptides_proteins_000005' WHERE group_id = 5 AND protein_id = 'sp|P48740|MASP1_' at line 1
And here is where the loop ends, because looking up this error online suggests to write something similar to the query at the top. Can anybody help me figure out a way to do this?
For me, there was not way to do this, so I had to put literal quotes around the %s.
My final code looked something like this:
assembly_name = peptide_protein_formatter(assembly_name)
mycursor = mydb.cursor()
qry = "SELECT peptide_id,search_id FROM %s WHERE group_id = %s AND protein_id = '%s'" % (assembly_name, group_id, protein_id)
mycursor.execute(qry)
result = mycursor.fetchall()

Python Querying on database with where clause

I am new to Python and want to understand the syntax for connecting to MS sql database.
Have successfully created the connection but want to select a conditional data.
Please suggest how can below be done in python:
import pyodbc as odbc
cursor.execute("SELECT Col1,Col2 FROM Data where date between sysdate and (sysdate-1) ;")
I have already assigned Start and end as :
End = dt.datetime.today()
Start = End - dt.timedelta(days=1)
How can this be incorporated in the query above??
Also, it would be really helpful if you could point me to some documentation where other such related things might be mentioned.
As explained in the pyodbc documentation for .execute, you can use ? as parameter placeholders in your SQL command text and pass the parameter values to .execute like so:
End = dt.datetime.today()
Start = End - dt.timedelta(days=1)
sql = "SELECT [Col1],[Col2] FROM [Data] WHERE [date] BETWEEN ? AND ?"
cursor.execute(sql, Start, End)
rows = cursor.fetchall()
I believe Gord's answer is the correct one but in case this is useful, you can also prepare dynamically you SQL statement within your Python code and provide the SQL statement already updated with the parameters to your cursor.
This should solve your error:
Error: ('HYC00', '[HYC00] [Microsoft][ODBC SQL Server Driver]Optional
feature not implemented (0) (SQLBindParameter)')
end = dt.datetime.today()
start = End - dt.timedelta(days=1)
sql = "SELECT [Col1],[Col2] FROM [Data] WHERE [date] BETWEEN '{}' AND '{}'".format(start, end)
cursor.execute(sql)
rows = cursor.fetchall()
Start = StringVar()
End = StringVar()
End = dt.datetime.today()
Start = End - dt.timedelta(days=1)
sql = "SELECT [Col1],[Col2] FROM [Data] WHERE [date] BETWEEN ? AND ?"
cursor.execute(sql, Start, End)
rows = cursor.fetchall()

Categories