我已經使用 Alchemy 和 pyobdc 成功連接了 SQL 服務器,更新資料庫,洗掉記錄也可以正常作業。
現在我想使用變數來分配SQL命令中的陳述句
#import library
import pandas as pd
import os
from sqlalchemy import create_engine
from sqlalchemy.engine import URL
import pyodbc
#prepare for the connection
SERVER = 'IT\SQLEXPRESS'
DATABASE = 'lab'
DRIVER = 'SQL Server Native Client 11.0'
USERNAME = 'sa'
PASSWORD = 'Welcome1'
DATABASE_CONNECTION = f'mssql://{USERNAME}:{PASSWORD}@{SERVER}/{DATABASE}?driver={DRIVER}'
#prepare SQL query
year_delete = 2019
sql_delete = ("DELETE FROM [dbo].table1 where dbo.table1.[Year Policy] = 2019")
result=connection.execute(sql_delete)
如何使用 year_delete 而不是在代碼中手動輸入 2019?
uj5u.com熱心網友回復:
正如Larnu在他們的評論中指出的那樣,使用 f 字串或其他字串格式化技術會使應用程式暴露于 SQL 注入攻擊,并且在任何情況下都可能容易出錯。
SQLAlchemy支持引數替換,允許將值安全地插入到 SQL 陳述句中。
from sqlalchemy import text
# Make a dictionary of values to be inserted into the statement.
values = {'year': 2019}
# Make the statement text into a text instance, with a placeholder for the value.
stmt = text('DELETE FROM [dbo].table1 where dbo.table1.[Year Policy] = :year')
# Execute the query.
result = connection.execute(stmt, values)
uj5u.com熱心網友回復:
您可以使用 f 字串(標準 python 技術插入 Python 運算式/變數):
sql_delete=(f"delete .... where dbo.table1[Year Policy] ={year_delete}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/461146.html
