【问题标题】:Fill SQL-SERVER table from an excel file从 excel 文件中填充 SQL-SERVER 表
【发布时间】:2018-08-14 14:41:39
【问题描述】:

我尝试通过执行以下 Python 脚本来使用 Python 填充 SQL SERVER 表:

import pyodbc 
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile

df = pd.read_excel('C:/Users/Username/Desktop/file1.xlsx', sheet_name='Sheet1')
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=MYSERVERNAME;"
                      "Database=DB;"
                      "uid=sa;pwd=MYPWD;"
                      "Trusted_Connection=yes;") 

print("Column headings:")
print(df.columns)
'''
for i in df.index:
    print(df['Last Name'][i],df['First Name'][i] )
'''
cursor = cnxn.cursor()
for i in df.index:
cursor.execute("insert into pyperson (id,firstname,lastname) values (df['ID'][i],df['First Name'][i],df['Last Name'][i])") 
cnxn.commit()  

PS:

If I try to read only data from excel file and then print it it works fine
if I try to insert directly with an insert into statement using python it works also fine 

但是当我将它们组合起来时,它会显示以下错误消息:

IndentationError: 需要一个缩进块

任何想法,任何帮助:)

【问题讨论】:

    标签: python sql sql-server tsql pyodbc


    【解决方案1】:

    我正在使用以下代码使用 Python 将数据从 txt 文件添加到 SQL Server,希望对您有所帮助:

    import pymssql
    import numpy as np
    
    host = 'YourHostName'
    username = 'USERNAME'
    password = 'PASSWORD'
    database = 'TestDB'
    
    conn = pymssql.connect(host, username, password, database)
    cursor = conn.cursor()
    cursor.execute("Delete from color_type")
    
    with open("Your file path\\filename.csv", "r") as ins:
        array=[]
        for line in ins:
            array.append(line)
            data = line.split('|')
            fst = data[0]
            lst = data[1]
            cursor.execute("insert into color_type values(%s, %s)", (fst, lst))
    
    cursor.execute("select * from color_type")
    rows = cursor.fetchall()
    conn.commit()
    print(rows) 
    

    【讨论】:

    • 如果我使用 excel 文件然后分号 (;) 应该是什么分隔符!?因为我也试过了,但显然它也不起作用
    • 您可以将该 excel 文件另存为 csv,然后使用该新 csv 文件的路径并将逗号 (,) 指定为分隔符。
    • 是的,这就是我所说的意思,我使用了分号。但它不起作用:/
    • @MohamedAzizi 您是否尝试将其保存为 csv 并使用 , 作为分隔符?
    • 是的,实际上是因为它只是为了学习目的,我什至尝试将其转换为文本文件,但它也不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多