繁体   English   中英

从Excel文件填充SQL-SERVER表

[英]Fill SQL-SERVER table from an excel file

我试图通过执行以下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将数据从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) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM