AttributeError:'Engine'对象没有属性'conn'

时间:2020-01-07 14:38:49

标签: python sqlalchemy xlrd

因此,我试图通过另一个值从另一个Excel文件创建对SQL的自动更新,以了解要添加到数据库中的新数据是什么。

数据库和excel文件之间的列名与数据库中的列名不同,并且名称之间没有空格...

我试图用大熊猫做它给了我同样的错误

这是我在xlrd上尝试过的简单代码

import xlrd
from sqlalchemy import create_engine


def insert():

    book = xlrd.open_workbook(r"MNM_Rotterdam_5_Daily_Details-20191216081027 - Copy (2).xlsx")
    sheet = book.sheet_by_name("GSM Details")

    database = create_engine(
    'mssql+pyodbc://WWX542337CDCD\SMARTRNO_EXPRESS/myDB?driver=SQL+Server+Native+Client+11.0')  # name of database


    cnxn = database.raw_connection
    cursor = cnxn.cursor()




    query = """Insert INTO [myDB].[dbo].[mnm_rotterdam_5_daily_details-20191216081027] (Date, SiteName, CellCI, CellLAC, CellName, CellIndex) values (?,?,?,?,?,?)"""


    for r in range(1, sheet.nrows):
        date = sheet.cell(r,0).value
        site_name = sheet.cell(r,3).value
        cell_ci = sheet.cell(r,4).value
        cell_lac = sheet.cell(r,5).value
        cell_name = sheet.cell(r,6).value
        cell_index = sheet.cell(r,7).value


        values = (date, site_name, cell_ci, cell_lac, cell_name, cell_index)


        cursor.execute(query, values)
        cnxn.commit()

# Close the cursor
    cursor.close()

# Commit the transaction
    database.commit()

# Close the database connection
    database.close()

# Print results
    print ("")
    print ("")
    columns = str(sheet.ncols)
    rows = str(sheet.nrows)
    print ("Imported", columns,"columns and", rows, "rows. All Done!")
insert()

这是错误:

我尝试更改发现另一个错误的范围:

Traceback (most recent call last):
  File "D:/Tooling/20200207/uniquebcon.py", line 48, in <module>
    insert()
  File "D:/Tooling/20200207/uniquebcon.py", line 37, in insert
    database.commit()
AttributeError: 'Engine' object has no attribute 'commit'

我认为这与连接中的SQL-Alchemy有关

1 个答案:

答案 0 :(得分:1)

与其直接创建光标,

cursor = database.raw_connection().cursor()

您可以创建一个连接对象,然后从该对象创建光标,然后在该连接上调用.commit()

cnxn = database.raw_connection()
crsr = cnxn.cursor()
# do stuff with crsr ...
cnxn.commit()