How to handle and execute multiple SQL at once in Python? - python

I am trying to execute multiple query in a for-loop. So in each loop, if either query failed to execute, all queries in that loop will not commit to database and return the error message for failed query. Below is my code. Seems even there is one query failed to run, the others queries will still execute and commit the data to database. How can I change it to achieve what I want? Thanks
Code:
import mysql.connector
mydb = mysql.connector.connect()
cursor = mydb.cursor()
for i in country_list:
try:
query1 = "call_sp_insert_sth_1" //insert data to DB
query2 = "call_sp_insert_sth_2" //insert data to DB
query3 = "call_sp_insert_sth_3" //update data to DB
cursor.execute(query1)
cursor.execute(query2)
cursor.execute(query3)
mydb.commit()
except Exceptiion as err:
fail_list.append('error':err.msg)
continue
mysql.connector.close_connection(mydb)

This is how I would write your code.
import mysql.connector
mydb = mysql.connector.connect()
cursor = mydb.cursor()
query1 = "call_sp_insert_sth_1" //insert data to DB
query2 = "call_sp_insert_sth_2" //insert data to DB
query3 = "call_sp_insert_sth_3" //update data to DB
for i in country_list:
try:
with mydb.cursor() as curs:
cursor.execute(query1)
cursor.execute(query2)
cursor.execute(query3)
curs.close()
except Exception as err:
fail_list.append('error':err.msg)
else:
mydb.commit()
I tend to have my queries as variables outside the for loop with parameters, then populate the parameters in the loop.
myquery = '''select * from {}'''
for table in tables:
curs.execute(myquery.format(table))
The 'else' part only kicks off if there were no errors in the 'try' part.

You need to set the mydb connection to not auto-commit.
mydb.autocommit = False

Related

psycopg2 with Postgres fetchall works but not execute

I am trying to execute some Postgres queries with psycopg2.
import psycopg2
conn = psycopg2.connect(
host="test.postgres.database.azure.com",
database="postgres",
user="test",
password="test")
cur = conn.cursor()
sql = "select site_panel from test.ws_sites"
cur.execute(sql)
rows = cur.fetchall()
The query above works well and returns the data but the following query does not delete the table as intended.
cur.execute ("DROP TABLE IF EXISTS test.ws_sites")
Anything wrong I'm doing here?
A query that modifies table data or schema structure needs to be committed:
cur.execute ("DROP TABLE IF EXISTS test.ws_sites")
conn.commit()
Alternatively, place
conn.autocommit = True
after creating the connection.

PYODBC: I cannot run "GRANT SELECT ON AAA TO BBB", What I am doing wrong?

I am using pyodbc.
query = "GRANT SELECT ON ABC.PROJE TO [MYDOMAIN\USER_1];"
connection.autocommit = True
cursor = connection.cursor()
result = cursor.execute(query)
connection.commit()
cursor.close()
connection.close()
All I get is an exception:
No Results. Previous SQL was not a query.
Is this method wrong, or are there any other ways to do this operation?
Thanks,

How to querying in Snowflake using Python (SSO Authentication)?

I tried to connect snowflake(SSO Authentication) and get data from table.
But, When i run the code, i can login with my credentials in the pop-up browser window and it connect Snowflake, no response after that(the program neither terminate nor provide result).
Not sure, where am doing mistake, Pls help.
'''
import snowflake.connector
# Connecting to Snowflake using SAML 2.0-compliant IdP federated authentication
conn = snowflake.connector.connect(
user='G*****K',
account='abcdf',
authenticator='externalbrowser',
warehouse='abcdf',
database='abcdf',
schema='abcdf'
)
cur = conn.cursor()
sql = "select * from abcdf.ACCT limit 10"
x=cur.execute(sql)
cur.close()
print(x)
'''
I believe you are closing the cursor before the print;
try:
cur.execute("SELECT col1, col2 FROM test_table ORDER BY col1")
for (col1, col2) in cur:
print('{0}, {1}'.format(col1, col2))
finally:
cur.close()
Details: https://docs.snowflake.com/en/user-guide/python-connector-example.html#using-cursor-to-fetch-values
Results of the query are stored in cursor. The contents of cursor may then be stored in a local variable.
Also, best practice to close connection in the end.
https://www.psycopg.org/docs/cursor.html
import snowflake.connector
# Connecting to Snowflake using SAML 2.0-compliant IdP federated authentication
conn = snowflake.connector.connect(
user='G*****K',
account='abcdf',
authenticator='externalbrowser',
warehouse='abcdf',
database='abcdf',
schema='abcdf'
)
cur = conn.cursor()
sql = "select * from abcdf.ACCT limit 10"
cur.execute(sql)
print(cur.fetchall())
cur.close()
conn.close()

Prepared Statements in MySQL - Trying to remove a row results in ProgrammingError

I want to use prepared statements to remove a row from a table, but it results in an error: mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
Relevant code:
db = mysql.connector.connect(
host='localhost',
user='user',
database='web_board',
password='password',
auth_plugin='mysql_native_password'
)
crs = db.cursor()
# construct the query and remove post from the database
query = 'DELETE FROM posts WHERE postid=%s'
crs.execute(query, tuple(request.data))
db.commit()
crs.close()
db.close()
request.data looks like this: b'9b23f24e-ff4d-4113-85ae-ff8a4a5de3be'
As the documentation states, to use prepared statements, you should instantiate your cursor with following config:
crs = db.cursor(prepared=True)
Prepared statements executed with MySQLCursorPrepared can use the format (%s) or qmark (?) parameterization style.

cx_oracle executes without error, but does not delete data

I would to remove all customers who's names begin with SCH from my database. When I execute the code below it runs without error, but does not remove the data from the database.
cur = db.cursor()
sql = "DELETE FROM customers where IMAGE_ID like 'SCH%'"
cur.execute(sql)
after delete you need commit
conn = cx_Oracle.connect(...)
cur = db.cursor()
sql = "DELETE FROM customers where IMAGE_ID like 'SCH%'"
cur.execute(sql)
conn.commit()
cur.close()
conn.close()

Categories