簡體   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