I can successfully connect my python notebook with sql server this way :
JavaScript
x
11
11
1
from sqlalchemy import create_engine
2
import sqlalchemy as sa
3
import urllib
4
5
params = urllib.parse.quote_plus('''DRIVER={SQL Server Native Client 11.0};
6
SERVER= SERVER_NAME;
7
DATABASE= DATABASE_NAME;
8
TRUSTED_CONNECTION=YES;''')
9
10
engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params,case_sensitive=False)
11
Let’s take this sample dataframe :
JavaScript
1
7
1
df = pd.DataFrame(dict(Name=['abc','def','ghi'],Date=['2018-08-15','2019-08-15','2020-08-15'],Status=[True,False,True],Max=[0,0,8]))
2
3
Name Date Status Max
4
0 abc 2018-08-15 True 0
5
1 def 2019-08-15 False 0
6
2 ghi 2020-08-15 True 8
7
I have a sql table with the same columns, named table_name.
Objective :
I want to delete in table_name all the rows where a row in df has the same Name, same Date, same Status, and Max = 0 (only in table_name, not necessary in df)
I tried the following but it doesn’t work :
JavaScript
1
10
10
1
connection = engine.raw_connection()
2
for index,row in df.iterrows():
3
try:
4
cursor = connection.cursor()
5
sql_Delete_query = """Delete from table_name where Date = %s AND Name = %s AND Status = %s AND Max = 0"""
6
cursor.execute(sql_Delete_query, (row['Date'],row['Name'],row['Status']))
7
connection.commit()
8
except:
9
error = True
10
Could you please help me to understand what is wrong ?
Advertisement
Answer
Different libraries use different symbols for their placeholders. The one you are using apparently uses ?
instead of %s
.
JavaScript
1
2
1
sql_Delete_query = """Delete from table_name where Date = ? AND Name = ? AND Status = ? AND Max = 0"""
2