代码之家  ›  专栏  ›  技术社区  ›  Mohamed Azizi

从excel文件填充SQL-SERVER表

  •  0
  • Mohamed Azizi  · 技术社区  · 6 年前

    我尝试使用Python填充SQL SERVER表,方法是执行下面的Python脚本:

    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()  
    

    附言:

    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 
    

    缩进错误:应为缩进块

    任何想法,任何帮助:)

    1 回复  |  直到 6 年前
        1
  •  0
  •   Aura    6 年前

    我正在使用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)