如何处理从Dataframe到SQL的大整数

2024-09-30 16:38:59 发布

您现在位置:Python中文网/ 问答频道 /正文

数据帧DF_JSON中的StaffIdent和firmIdentit是大整数。例如,职员15423992539793905091 我想将数据从dataframe转换为SQL,当我将StaffIndent和FirmIndent视为字符串并将新数据与SQL中测试表中的当前数据合并时,就可以了。这项工作:

from sqlalchemy import create_engine, types
import os
import logging
import json
import pandas as pd
import sqlalchemy 
import pandasql as ps

def upload_data(SQLServer,SQLDatabase,JSON_file):
    Table_Name='TEST'
    engine = create_engine('mssql+pyodbc://{0}/{1}?driver=SQL Server?Trusted_Connection=yes'.format(SQLServer,SQLDatabase))
    i=0
    for JSON_file in os.listdir('Data/'+Table_Name):
        logging.info('Debug: Reading file JSON and inserting into database: {0}'.format(JSON_file))
        JSON = json.load(open('Data/'+Table_Name+'/'+JSON_file))
        DF_JSON=pd.DataFrame.from_dict(JSON,dtype=object)
        DF_JSON = DF_JSON.astype(str)

        try:
            if i==0:
                DF_JSON.to_sql(Table_Name,engine,if_exists='replace',chunksize=50,index=False,dtype={'StaffIdent':sqlalchemy.types.String, 'FirmIdent':sqlalchemy.types.String})
            else:
                DF_JSON.to_sql(Table_Name,engine,if_exists='append',chunksize=50,index=False,dtype={'StaffIdent':sqlalchemy.types.String, 'FirmIdent':sqlalchemy.types.String})
            print('Successfully')
        except Exception as ErrorMessage:
            logging.info(': Error occured when inserting records into DB: '+ErrorMessage+'.')

        return DF_JSON
        logging.info('Successfully uploaded JSON to SQL {}'.format(JSON_file))

问题是,将它们转换为字符串不是一种有效的方法,因为SQL中测试中的StaffIndent和FirmIndent最初是数字。我的问题是:如何处理BigInt,并将它们作为数字处理

用BigInteger替换字符串时:

        try:
            if i==0:
                DF_JSON.to_sql(Table_Name,engine,if_exists='replace',chunksize=50,index=False,dtype={'StaffIdent':sqlalchemy.types.BigInteger, 'FirmIdent':sqlalchemy.types.BigInteger})
            else:
                DF_JSON.to_sql(Table_Name,engine,if_exists='append',chunksize=50,index=False,dtype={'StaffIdent':sqlalchemy.types.BigInteger, 'FirmIdent':sqlalchemy.types.BigInteger})

错误:

DataError: (pyodbc.DataError) ('22003', '[22003] [Microsoft][ODBC SQL Server Driver][SQL Server]Arithmetic overflow error converting expression to data type bigint. (8115) (SQLExecDirectW); [22003] [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated. (3621)')

使用十进制听起来不错,但不是,数据类型必须是数字&;在SQL中使用整数

                DF_JSON.to_sql(Table_Name,engine,if_exists='replace',chunksize=50,index=False,dtype={'StaffIdent':sqlalchemy.types.DECIMAL(38,0), 'FirmIdent':sqlalchemy.types.DECIMAL(38,0)})
            else:
                DF_JSON.to_sql(Table_Name,engine,if_exists='append',chunksize=50,index=False,dtype={'StaffIdent':sqlalchemy.types.DECIMAL(38,0), 'FirmIdent':sqlalchemy.types.DECIMAL(38,0)})

Tags: tonameimportjsondfsqlifsqlalchemy
2条回答

没有@ConfigurationCondition@Condition注释,只有@Conditional。对于@Conditional,可以指定ConditionConfigurationCondition

@Conditional根据条件确定是启用还是禁用@Configuration类。作为documentation says最好的例子是@Profile注释本身,它根据所选的配置文件确定加载或不加载哪些bean

ConfigurationCondition考虑的两个阶段是@Configuration类经历的阶段:首先解析类,然后注册和创建bean

^{}Condition类的@Configuration特化

纯^ ^ {CD2>}对于99%的用例来说是很好的,所以你应该首先考虑。专门化实际上是确定应该在@Configuration类的处理的阶段评估条件

分为两个阶段:

  • PARSE_CONFIGURATION在分析@Configuration注释的类时计算条件。这样就有机会完全排除配置类
  • REGISTER_BEAN在注册配置类中的bean时计算条件。这不会阻止添加配置类,但如果条件不匹配(由Condition接口的matches方法定义),它允许跳过bean定义

Spring Boot有一个OnBeanCondition,基本上在注册阶段检查是否存在另一个bean。这是ConditionalOnBean的核心,当有bean时,它基本上会做一些事情

相关问题 更多 >