Python SQL Alchemy 코어를 사용하여 Microsoft SQL Server에서 간단한 병합 조인 쿼리를 실행하려고합니다.
먼저 서버 관리 스튜디오를 사용하여 수행하는 방법을 설명하겠습니다.
MERGE [Database1].[Schema1].[Table1] table1
USING [Database2].[Schema2].[Table2] table2
ON table1.[Key] = table2.[Key]
WHEN MATCHED THEN
UPDATE
SET table1.[Column] = table2.[Column];
이것은 잘 작동하고 Column
성공적으로 설정되었습니다.
그러나 파이썬을 사용하여 이것을 할 때 :
DB_TARGET = {
'drivername': 'mssql+pyodbc',
'servername': 'localhost',
'port': '1443',
'username': 'user1',
'password': 'pass',
'driver': 'ODBC Driver 13 for SQL Server',
'trusted_connection': 'yes',
'legacy_schema_aliasing': False
}
params = urllib.parse.quote_plus("DRIVER={" + DB_TARGET['driver'] + "}" +
";SERVER=" + DB_TARGET['servername'] +
";UID=" + DB_TARGET['username']+
";PWD=" + DB_TARGET['password'])
engine1 = create_engine( DB_TARGET['drivername'] + ":///?odbc_connect=%s" % params)
metadata = MetaData(bind=engine1)
conn = engine1.connect()
q="MERGE [Database1].[Schema1].[Table1] table1 \
USING [Database2].[Schema2].[Table2] table2 \
ON table1.[Key] = table2.[Key] \
WHEN MATCHED THEN \
UPDATE \
SET table1.[Column] = table2.[Column];"
conn.execute(q)
conn.close()
아무 일도 일어나지 않고 예외가 발생 Column
하지 않으며 값이 영향을받지 않습니다.
SQL Server 프로파일 러를 확인하고 쿼리가 제출되고 있는지 확인했습니다.
다음과 같이 더 간단한 쿼리를 실행 해 보았습니다.
q="SELECT * FROM TABLE1"
잘 작동합니다.
여기서 문제는 무엇입니까?
SQLAlchemy는 기본적으로 MERGE 문을 데이터 변경 작업으로 인식하지 않으므로 .NET Framework를 사용하지 않고 연결을 사용할 때 커밋을 실행하지 않습니다 Transaction
. "Understanding Autocommit"을 읽어야 합니다. 따라서 명시 적 트랜잭션을 사용하십시오.
with conn.begin() as trans:
conn.execute(q)
또는이 명령문이 자동 커밋되어야한다고 SQLAlchemy에 알립니다.
conn.execute(text(q).execution_options(autocommit=True))
따로, 파이썬은 특별히 개행 문자를 피하고 싶지 않다면 백 슬래시없이 삼중 따옴표가있는 여러 줄 문자열을 지원합니다.
q = """MERGE [Database1].[Schema1].[Table1] table1
USING [Database2].[Schema2].[Table2] table2
ON table1.[Key] = table2.[Key]
WHEN MATCHED THEN
UPDATE
SET table1.[Column] = table2.[Column];"""
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다