如何在 SQL Alchemy 中使用变量
How to use variable in SQL Alchemy
我已经使用 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?
您可以使用 f-string(标准 python-technique 插入 Python-Expressions/Variables):
sql_delete=(f"delete .... where dbo.table1[Year Policy] ={year_delete}")
与 Larnu points out in their 一样,使用 f-strings 或其他字符串格式化技术会使应用程序暴露于 SQL 注入攻击,并且在任何情况下都可能 error-prone.
SQLAlchemy supports parameter substitution,允许将值安全地插入到 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)
我已经使用 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?
您可以使用 f-string(标准 python-technique 插入 Python-Expressions/Variables):
sql_delete=(f"delete .... where dbo.table1[Year Policy] ={year_delete}")
与 Larnu points out in their
SQLAlchemy supports parameter substitution,允许将值安全地插入到 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)