SQL Alchemy、pymssql、Pandas 0.24.2 to_sql 尝试在表已存在时创建表

2024-03-16

我正在尝试使用 Pandas 和 Sql Alchemy。这基本上就是我想做的事情。如果我删除该表,它会创建它,但我希望它追加而不需要进行表重命名。我尝试过更新和更改所有库的版本。我很茫然。如果我一开始没有表,它会创建它,然后我再次运行代码,它就会崩溃。错误消息只是说该表已经存在,我知道,这就是为什么我告诉它追加。另外,在加载之前,我正在使用 PYMSSQL 读取数据,并且它可以很好地读取数据帧

Python命令

def writeDFtoSSDatabase(tgtDefiniton,df):
try:
    if int(tgtDefiniton.loadBatchSize) > 0:
        batchSize = int(tgtDefiniton.loadBatchSize)
    else:
        batchSize = 1000
    #Domain error using SQL Alchemy
    logging.debug("Writting Dataframe to SQL Server database")
    #hardcoded type beccause that is only type for now
    with createDBConnection(tgtDefiniton.tgtDatabaseServer
                                ,tgtDefiniton.tgtDatabaseDatabase
                                ,tgtDefiniton.tgtDatabaseUser
                                ,tgtDefiniton.tgtDatabasePassword,tgtDefiniton.tgtDataType).connect().execution_options(schema_translate_map={
                                                                                                                        None: tgtDefiniton.tgtDatabaseSchema}) as conn:
        logging.debug("Writting DF to Database table {0}".format(tgtDefiniton.tgtDatabaseTable))
        logging.debug("ifTableExists: {0}.".format(tgtDefiniton.ifTableExists))
        
        if tgtDefiniton.ifTableExists == "append":
            logging.debug('Appending Data')
            df.to_sql(tgtDefiniton.tgtDatabaseTable,con=conn,if_exists='append',chunksize = batchSize,index=False)
        elif tgtDefiniton.ifTableExists == "replace":
            logging.debug('Replacing Table and Data')
            df.to_sql(tgtDefiniton.tgtDatabaseTable,con=conn,if_exists='replace',chunksize = batchSize,index=False)
        else:
            df.to_sql(tgtDefiniton.tgtDatabaseTable,con=conn,if_exists='fail',index=False)
        logging.debug("Data wrote to database")
except Exception as e:
    logging.error(e)
    raise

Error

(Background on this error at: http://sqlalche.me/e/e3q8)
2021-08-30 13:31:42 ERROR    (pymssql.OperationalError) (2714, b"There is already an object 
named 'test' in the database.DB-Lib error message 20018, severity 16:\nGeneral SQL Server 
error: Check messages from the SQL Server\n")

编辑: 日志条目

  2021-08-30 13:31:36 DEBUG    Writting Dataframe to SQL Server database
  2021-08-30 13:31:36 DEBUG    create_engine(mssql+pymssql://REST OF             CONNECTION INFO
  2021-08-30 13:31:36 DEBUG    DB Engine Created
  2021-08-30 13:31:36 DEBUG    Writting DF to Database table test
  2021-08-30 13:31:36 DEBUG    ifTableExists: append.
  2021-08-30 13:31:36 DEBUG    Appending Data
  2021-08-30 13:31:42 ERROR    (pymssql.OperationalError) (2714, b"There is already an object named 'test' in the database.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n")

[SQL:


我遇到了同样的问题,我找到了两种方法来解决它,尽管我不知道为什么会解决它:

  1. 要么在创建连接时在url中传递数据库名称
  2. 或将数据库名称作为模式传递pd.to_sql.

两者都做并没有坏处。

```
#create connection to MySQL DB via sqlalchemy & pymysql
user = credentials['user']
password = credentials['password']
port = credentials['port']
host = credentials['hostname']
dialect = 'mysql'
driver = 'pymysql'
db_name = 'test_db'

# setup SQLAlchemy   
from sqlalchemy import create_engine 
cnx = f'{dialect}+{driver}://{user}:{password}@{host}:{port}/' 
engine = create_engine(cnx) 

# create database
with engine.begin() as con:
    con.execute(f"CREATE DATABASE {db_name}")

############################################################
# either pass the db_name  vvvv - HERE- vvvv after creating a database
cnx = f'{dialect}+{driver}://{user}:{password}@{host}:{port}/{db_name}'      
############################################################
engine = create_engine(cnx) 

table = 'test_table'
col = 'test_col'
with engine.begin() as con:
    # this would work here instead of creating a new engine with a new link
    # con.execute(f"USE {db_name}")
    con.execute(f"CREATE TABLE {table} ({col} CHAR(1));")

# insert into database
import pandas as pd
df = pd.DataFrame({col : ['a','b','c']})

with engine.begin() as con:
    # this has no effect here
    # con.execute(f"USE {db_name}")
    df.to_sql(
        name= table,
        if_exists='append',
        con=con, 
############################################################
# or pass it as a schema vvvv - HERE - vvvv
        #schema=db_name,
############################################################
        index=False
    )```

使用python版本测试3.8.13和 sqlalchemy1.4.32。 可能出现了同样的问题here https://stackoverflow.com/questions/26765863/python-pandas-to-sql-append and here https://stackoverflow.com/questions/69906698/pandas-to-sql-gives-table-already-exists-error-with-if-exists-append.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SQL Alchemy、pymssql、Pandas 0.24.2 to_sql 尝试在表已存在时创建表 的相关文章

  • 修复类以在 Flask 会话中启用对象存储[重复]

    这个问题在这里已经有答案了 我有一个自定义类 Passport 其中包含活动用户身份和权限 我曾经将它存储在会话中 如下所示 p Passport p do something fancy session passport p 它就奏效了
  • 在Python中迭代文件对象不起作用,但readlines()可以,但效率低下

    在下面的代码中 如果我使用 for line in fin 它只对 a 执行 但如果我使用 wordlist fin readlines for line in wordlist 然后它执行 a thru z But readlines 立
  • SQL:计算高于组平均值的值

    如何使用 SQL 计算高于一组平均值的值 例如 我有桌子A with q t 1 5 1 6 1 2 1 8 2 6 2 4 2 3 2 1 第 1 组的平均值为 5 25 组内有两个值高于5 25 8和6 因此高于该组平均值的值的数量为
  • __getitem__、__setitem__ 如何处理切片?

    我正在运行 Python 2 7 10 我需要拦截列表中的更改 我所说的 更改 是指在浅层意义上修改列表的任何内容 如果列表由相同顺序的相同对象组成 则列表不会更改 无论这些对象的状态如何 否则 它会更改 我不需要找出来how列表已经改变
  • 使用Python进行图像识别[关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我有一个想法 就是我想识别图像中的字母 可能是 bmp或 jpg 例如 这是一个包含字母 S 的 bmp 图像 我想做的是使用Pyth
  • 使用 OpenCV 进行相机校准 - 如何调整棋盘方块大小?

    我正在使用 OpenCV Python 示例开发相机校准程序 来自 OpenCV 教程 http opencv python tutroals readthedocs io en latest py tutorials py calib3d
  • 将分布拟合到直方图

    I want to know the distribution of my data points so first I plotted the histogram of my data My histogram looks like th
  • 获取 HTML 代码的结构

    我正在使用 BeautifulSoup4 我很好奇是否有一个函数可以返回 HTML 代码的结构 有序标签 这是一个例子 h1 Simple example h1 p This is a simple example of html page
  • 如何将字符串方法应用于数据帧的多列

    我有一个包含多个字符串列的数据框 我想使用对数据帧的多列上的系列有效的字符串方法 我希望这样的事情 df pd DataFrame A 123f 456f B 789f 901f df Out 15 A B 0 123f 789f 1 45
  • 如何在 Python 中将 EXR 文件的 float16 转换为 uint8

    我正在使用 OpenEXR 读取 Python 中的 EXR 文件 我有带有半数据 float16 的 R G 和 B 通道 我尝试使用 Numpy 将数据从 float16 转换为 uint8 0 255 颜色 但没有成功 rCh get
  • T-SQL参数嗅探重新编译计划

    我有 SQL 命令 exec sp executesql N SELECT TOP 10 FROM mytableView WHERE Name LIKE Value0 ORDER BY Id DESC N Value0 varchar 5
  • django 中的“管理器”是什么?

    我已经阅读了Django官方中的定义文档 https docs djangoproject com en dev topics db managers 我仍然对什么感到困惑Manager does 文档说它们允许您操作数据库表 模型 但我仍
  • 如何让 Python 找到 ffprobe?

    I have ffmpeg and ffprobe安装在我的 mac macOS Sierra 上 并且我已将它们的路径添加到 PATH 中 我可以从终端运行它们 我正在尝试使用ffprobe使用以下代码获取视频文件的宽度和高度 impor
  • 我可以将 UseCSharpNullComparisonBehavior 用于单个查询吗?

    我有一个查询 该查询曾经是存储过程 现已转换为 EF 查询 现在已经超时了 使用 SQL Profiler 我可以看到生成的 SQL 的唯一区别是 EF 转变的新行为entity Property value into entity Pro
  • 无法在 Windows 服务器上使 SVN 预提交脚本失败

    我正在编写一个 SVN pre commit bat 文件 该文件调用 Python 脚本来查询我们的问题跟踪系统 以确定用户提供的问题跟踪 ID 是否处于正确的状态 例如 打开 状态 并与正确的关联项目 SVN 服务器运行 Windows
  • 为什么 tesseract 无法从这个简单的图像中读取文本?

    我在 pytesseract 上阅读了大量的帖子 但我无法让它从一个简单的图像中读取文本 它返回一个空字符串 这是图像 我尝试过缩放它 灰度化它 调整对比度 阈值 模糊 以及其他帖子中所说的一切 但我的问题是我不知道 OCR 想要更好地工作
  • Python中的MariaDB连接器无法连接到远程服务器

    我使用与远程 Mariadb 服务器的连接已有几个月了 今天 无法再通过 macOS 上的 python mariadb 模块和 mariadb 连接器建立连接 基本安装如下 brew install mariadb connector c
  • 用户的完整 UNIX 用户名

    想知道您是否知道是否有一种巧妙的方法可以从 shell 获取完整的用户名 示例 如果我的 UNIX 用户名是 froyo 那么我想获取我的全名 在本例中 如系统中注册的那样 froyo Abhishek Pratap Finger 命令可以
  • Matplotlib 渲染日期、图像的问题

    我在使用 conda forge 的 Matplotlib v 3 1 3 和 python 3 7 时遇到问题 我拥有 Matplotlib 所需的所有依赖项 当我输入这段代码时 它应该可以工作 我得到了泼溅艺术 它基于此 YouTube
  • Pandas DataFrame 自定义 agg 函数奇怪的行为

    我想使用自定义函数沿轴聚合 Pandas DataFrame 但我无法弄清楚该函数应返回什么 df pd DataFrame np arange 50 reshape 10 5 您可以将 numpy 函数传递给DataFrame agg C

随机推荐