[使用python在SQL数据库中创建表

问题描述 投票:0回答:1

实际上,我想使用python在SQL数据库中创建一个表。下面是我的代码。我当前面临的问题是,以下代码仅在数据库中已经存在“ HeaderTable”时才起作用(我手动创建了带有列的空表),然后才将数据框值导出到数据库。但是,当数据库中没有表时,我将得到以下错误。有人可以帮我吗?

import pandas as pd
import pyodbc

eventcode_to_DB = pd.read_excel("C:\\ABB\\Productivity Improvement\\Standard Support Automation\\Files\\Reference Files\\Event description_Rev2.xlsx",index=False)

def transfer_local_db():
    try:
        cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=10.140.175.221;DATABASE=StdSupport;UID=sa;PWD=ReportSiu@13418')
        cursor = cnxn.cursor()
        cursor.execute('''IF EXISTS
           (  SELECT *
              FROM sys.tables
              WHERE [name] = 'HeaderTable'
              and schema_id = schema_id('StdSupport')
           )
           CREATE TABLE [StdSupport].[dbo].[HeaderTable](EventCode INT,
                                                            Domain VARCHAR(255),
                                                            Header VARCHAR(255),
                                                            ControllerTypeName VARCHAR(255),
                                                            concatenated1 VARCHAR(255))

        ''')
        cursor.executemany(
        '''INSERT INTO [StdSupport].[dbo].[HeaderTable] (EventCode,
                                                            Domain,
                                                            Header,
                                                            ControllerTypeName,
                                                            concatenated1) VALUES (?, ?, ?, ?, ?)''',list(eventcode_to_DB.itertuples(index=False, name=None)))

        cursor.commit()
        cursor.close()
        cnxn.commit()
        cnxn.close()
        print("Data stored in local database.")
    except pyodbc.Error as err:
        sqlstate = err.args[1]
        print("Data not stored in the local databse due to: ")
        print(sqlstate)

if __name__== "__main__":
    transfer_local_db()

由于机密信息,我将无法共享数据。

错误:-文件“”,第21行,在 concatenated1)值(?,?,?,?,?)''',list(eventcode_to_DB.itertuples(index = False,name = None))]

ProgrammingError:('42S02',“ [42S02] [Microsoft] [ODBC SQL Server 驱动程序] [SQL Server]无效的对象名称“ StdSupport.dbo.HeaderTable”。 (208)(SQLExecDirectW); [42S02] [Microsoft] [ODBC SQL Server 无法准备驱动程序[SQL Server]语句。 (8180)“)

sql-server python-3.x pyodbc
1个回答
0
投票

例如,在没有[dbo]的情况下尝试使用

CREATE TABLE [StdSupport].[HeaderTable]
© www.soinside.com 2019 - 2024. All rights reserved.