python read table_Python pandas 模块,read_sql_table() 实例源码 - 编程字典

def table_archiver(server, database, source_table, destination_table, timestamp_column_name='ArchivedDTS'):

"""

Takes a table and archives a complete copy of it with the addition of a timestamp of when the archive occurred to a

given destination table on the same database.

This should build a new table if the table doesn't exist.

Args:

server (str): Server name

database (str): Database name

source_table (str): Source table name

destination_table (str): Destination table name

timestamp_column_name (str): New timestamp column name

Returns:

(str): A string with details on records archived.

Example usage:

from healthcareai.common.table_archiver import table_archiver

table_archiver('localhost', 'SAM_123', 'RiskScores', 'RiskScoreArchive', 'ArchiveDTS')

```

"""

# Basic input validation

if type(server) is not str:

raise HealthcareAIError('Please specify a server address')

if type(database) is not str:

raise HealthcareAIError('Please specify a database name')

if type(source_table) is not str:

raise HealthcareAIError('Please specify a source table name')

if type(destination_table) is not str:

raise HealthcareAIError('Please specify a destination table name')

start_time = time.time()

connection_string = 'mssql+pyodbc://{}/{}?driver=SQL+Server+Native+Client+11.0'.format(server, database)

# Load the table to be archived

df = pd.read_sql_table(source_table, connection_string)

number_records_to_add = len(df)

# Add timestamp to dataframe

df[timestamp_column_name] = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')

# Save the new dataframe out to the db without the index, appending values

df.to_sql(destination_table, connection_string, index=False, if_exists='append')

end_time = time.time()

delta_time = end_time - start_time

result = 'Archived {0} records from {1}/{2}/{3} to {4} in {5} seconds'.format(

number_records_to_add,

server,

database,

source_table,

destination_table,

delta_time)

return result

```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值