This question already has answers here:
Execute a PL/SQL function (or procedure) from SQLAlchemy
(2 answers)
stored procedures with sqlAlchemy
(8 answers)
Closed 4 years ago.
I wrote this function to take in three parameters and a database connection, execute a function, and then pull from a view that is populated by the function.
def get_customer_data(start_date, end_date, segment, con):
""" Get customer data
"""
# This executes a process in the database that populates
# my_view which we will subsequently pull from.
sql = """EXEC PROCESS_POPULATE_VIEW ('%s','%s','%s');
""" % (str(start_date), str(end_date), segment)
con.execute(sql)
sql = "SELECT * FROM MY_VIEW"
return pd.read_sql(sql, con)
This is what I get back:
DatabaseError: (cx_Oracle.DatabaseError) ORA-00900: invalid SQL statement [SQL: "EXEC PROCESS_POPULATE_VIEW ('11-JUN-2018','13-JUN-2018','Carrier');\n "] (Background on this error at: http://sqlalche.me/e/4xp6)
Am I not allowed to call the EXEC command from sqlalchemy? Is there a workaround for this?
Related
This question already has answers here:
Python mySQL Update, Working but not updating table
(3 answers)
Closed 3 months ago.
I have a MySQL database instance hosted on GCP, and I am connecting to it using the pymysql python package. I would like to delete some rows from a database table called Basic.
The code I have written to do this is included below. The variable conf contains the connection details to the database instance.
import pymysql
import pandas as pd
# Establish connection.
connection = pymysql.connect(**conf)
cursor = connection.cursor()
# Delete rows of table.
try:
cursor.execute("DELETE FROM Basic WHERE Date = '2022-11-25 04:00:00';")
except Exception as ex:
print("Exception occured: %s" %ex)
finally:
connection.close()
# Check the table to see if deletion has occurred.
connection = pymysql.connect(**conf)
cursor = connection.cursor()
cursor.execute("SELECT * FROM Basic WHERE Date = '2022-11-25 04:00:00'")
connection.close()
df = pd.DataFrame(cursor.fetchall(), columns = ["Date", "State", "Price", "Demand"])
Clearly one would expect the dataframe defined here to have no rows, but this is not the case. This shows that the SELECT statement included in the code above produces the expected result, but the corresponding DELETE statement does not.
Why is this the case?
The code above requires the addition of the following line, in order to commit the DELETE statement.
connection.commit()
The commit method should be called after every transaction that modifies data, such as this one.
This question already has answers here:
Not all parameters were used in the SQL statement (Python, MySQL)
(5 answers)
Closed last year.
error imageActually I am trying to create flask web application in which, I wanted to store my input values from html webpage into MySQL database, but am getting error as Not all parameters were used in the SQL statement when calling my insert function.
Please find my code
import mysql.connector as conn
def insert_records(name,email,location,salary,band):
con=conn.connect(host='localhost',user='root',password='my password',database="my database")
cur=con.cursor()
sql="""insert into emp1.emp(Name,Email,Location,Salary,Band) values (%s,%s,%s,%d,%s)"""
val=(name,email,location,salary,band)
cur.execute(sql,val)
con.commit()
con.close()
You need to use %s for every argument per the documentation - they use %s for strings, integers, datetimes, etc.
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
This question already has answers here:
Python SQLite how to get SQL string statement being executed
(4 answers)
Closed 2 years ago.
Here I see the suggested way of building queries with python and sqlite3:
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print(c.fetchone())
How do I print the query instead of the result? I know it's not a string, and so a "print sql" statement wouldn't work. In my case, I am running flask and I want to have this code responding to an API invocation:
...
cur = conn.cursor()
arguments = (username, password, )
query = 'SELECT * FROM logins where ((username = ?) AND (password = ?));', arguments
return(query)
...
I would expect to see this query, not to execute it. However, I receive this output:
ValueError: too many values to unpack (expected 2)
Furthermore, I didn't see any method that exports the last query issued in the SQLite.
This might not be the answer you're looking for, but you can format the query as a string using python string format and print, before formatting again using db-api within the c.execute() statement. As long as you only format the executed query with db-api, you're not at risk from sql injection.
This question already has answers here:
How to use variables in SQL statement in Python?
(5 answers)
Closed 4 years ago.
I am attempting to write an SQL query to update the password of a user currently logged into a web application. I am using a session ID to identify the specific user to which to update the password for. However, I am unsure of how to write the correct syntax for the query
Here is the query in question:
cursor.execute("UPDATE user SET password = %s WHERE email = ?", [confirm_password], session['email'])
And the error being generated as a result:
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 '?' at line 1
I would like to update only the password of the user who is logged in using the session ID their username(in this case an email address).
Any help would be appreciated. Thanks.
You need to supply them as tuple of values to be inserted in your execute statement.
Syntax looks like this: cursor.execute(operation, params=None, multi=False)
operation is your query string
params is a tuple containing all params inside it
cursor.execute("UPDATE user SET password = %s WHERE email = %s",
(confirm_password, session['email']) )
and you probably also should use % twice..
See connector-python-api-mysqlcursor-execute
When in doubt, I lookup syntax here: http://bobby-tables.com/python or use the original doku.
This question already has answers here:
SQLAlchemy support of Postgres Schemas
(12 answers)
SQLAlchemy: engine, connection and session difference
(3 answers)
Closed 5 years ago.
I am working with a Postgres database. This database has three schemas (schema_1, schema_2, public). If I run a simple query, the public schema will be queried by default:
from sqlalchemy import create_engine
con = create_engine('postgresql+pg8000://usr:pwd#server/db')
con.execute('select count(*) from the_table')
I cannot access the tables in schema_1 or schema_2, unless I specify the path in the query:
con.execute('select count(*) from schema_1.the_table')
Is there any way to specify the default path of the query to schema_1 without the need of specifying the full path in the query itself?
I tried with:
con.execute('SET search_path TO "schema_1";')
but this does not seem to work:
insp = inspect(con)
print(insp.default_schema_name)
# 'public'
I believe I am not executing the SET search_path TO "schema_1" correctly because the same command does work in other Postgres clients (like pgAdmin)