簡體   English   中英

如何在 Python 中使用 SQLAlchemy 識別數據庫連接字符串上的模式?

[英]How to identify schema on database connection string using SQLAlchemy, in Python?

我有這段代碼使用 SQLAlchemy 連接到數據庫。 我只有一個模式(dbo),所以效果很好。 現在我必須架構。 我一直在嘗試調整這段代碼來識別連接上的模式,但我無法讓它工作。 任何人都可以幫忙嗎?


from datetime import datetime
from sqlalchemy import create_engine
import urllib
import time
import logging


server = "xxx"
username = "xxx"
password = "xxx"
database = "db_name"
driver = "{ODBC Driver 17 for SQL Server}"


#to measure total elapsed time of the script
start_time = round(time.time(),2)

#datetime manipulation to send to table
run_time_start = datetime.now().isoformat(" ", "seconds")

#Logging Information Configuration
logging.basicConfig(filename='ControlX.log', level=logging.DEBUG,
                    format='%(asctime)s++%(levelname)s++%(message)s')

#to measure db connection time
start_time_db = round(time.time(),2)


#Connection object for connection to sql database to send files
print( "Connecting to database..." )
params = urllib.parse.quote_plus(
'Driver=%s;' % driver +
'Server=tcp:%s,1433;' % server +
'Database=%s;' % database +
'Uid=%s;' % username +
'Pwd={%s};' % password +
'Encrypt=yes;' +
'TrustServerCertificate=no;' +
'Connection Timeout=60;')

conn_str = 'mssql+pyodbc:///?odbc_connect=' + params

engine = create_engine(conn_str,echo=False, fast_executemany=True)
logging.info("Database Connection++Database++{}".format(round(time.time()-start_time_db, 2)))

print("Database connection succeeded")

listLog=[]
#log information treatment
with open("ControlX.log",'r') as data_file:
    for line in data_file:
        line_list = line.rstrip('\n').split("++")
        line_list[0] = line_list[0][:-4]
        listLog.append(line_list)
     
for item in listLog:
    item[4] = float(item[4])

#insert logging information about DATABASE CONNECTION ELAPSED TIME in database
engine.execute('INSERT INTO tableX (log_date, log_type, message, obj, total_time) VALUES (?, ?, ?, ?, ?)', listLog)

您可以通過更改執行代碼來嘗試

engine.execute('INSERT INTO [database].[schemaName].tableX (log_date, log_type, message, obj, total_time) VALUES (?, ?, ?, ?, ?)', listLog)

或者

   engine.execute('INSERT INTO [schemaName].tableX (log_date, log_type, message, obj, total_time) VALUES (?, ?, ?, ?, ?)', listLog)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM