_mssql.MSSQLDatabaseException:(207,b“无效的列名'Hello'.DB-Lib错误消息20018

时间:2018-06-29 05:37:07

标签: python sql-server python-3.x

我想将记事本的数据插入数据库,但是出现错误:

  

回溯(最近一次通话最后一次):文件“ src \ pymssql.pyx”,行448,   在pymssql.Cursor.execute文件“ src_mssql.pyx”的第1061行中   _mssql.MSSQLConnection.execute_query文件“ src_mssql.pyx”中的“ src_mssql.pyx”文件,第1092行,   _mssql.MSSQLConnection.format_and_run_query文件中的第1225行   _mssql.check_cancel_and_raise文件中的“ src_mssql.pyx”行1636   在第1680行的“ src_mssql.pyx”中   _mssql.maybe_raise_MSSQLDatabaseException   _mssql.MSSQLDatabaseException:(207,b“无效的列名'Hello'.DB-Lib错误消息20018,严重性16:\ n常规SQL Server   错误:检查来自SQL Server的消息\ n“

我的python代码:

# -*- coding: UTF-8 -*-
import pandas as pd
import pymssql
def insert_report_pn_dictionary(server, user, password, database):
    pn_df = pd.read_csv(r'D:/20180605_dict.txt', \
                        sep=':',
                        encoding='utf-8',
                        names=('Word', 'Reading', 'POS', 'PN')
                        )
    word_list = list(pn_df['Word'])
    pn_list = list(pn_df['PN'])
    pn_dict = dict(zip(word_list, pn_list))
    dict_list = []
    for key,value in  pn_dict.items():
        dict_list.append([key,value])
    try:
        conn = pymssql.connect(server, user, password, database)
        cur = conn.cursor()
        for item in dict_list:
            sql = ' insert into report_pn_dictionary (dict_keyword, dict_pn) ' \
                  ' values(%s, %s) ' % (item[0], item[1])
            cur.execute(sql)
            conn.commit()
    except pymssql.Error as ex:
        raise ex
    except Exception as ex:
        raise ex
    finally:
        conn.close()

if __name__=="__main__":
    server = '10.10.2.20'
    user = 'test'
    password = 'test'
    database = 'DBAL'
    insert_report_pn_dictionary(server, user, password, database)

20180605_dict.txt的内容:

  

你好:a1:a1:0.999979

     

大:a2:a2:0.999645

     

Apple:a3:a3:0.999486

表report_pn_dictionary的结构:

CREATE TABLE [dbo].[report_pn_dictionary](
    [dict_keyword] [nvarchar](50) NOT NULL,
    [dict_pn] [decimal](18, 10) NULL,
    [registered] [datetime] NULL,
    [modified] [datetime] NULL
)

哪里出了问题?如何解决?

2 个答案:

答案 0 :(得分:0)

我不知道哪里出了问题,但是现在我使用“ executemany”,那么就没有错误。

修改后的代码:

# -*- coding: UTF-8 -*-
import pandas as pd
import pymssql

def insert_report_pn_dictionary(server, user, password, database):
    pn_df = pd.read_csv(r'D:/20180605_dict.txt', \
                        sep=':',
                        encoding='utf-8',
                        names=('Word', 'Reading', 'POS', 'PN')
                        )
    word_list = list(pn_df['Word'])
    pn_list = list(pn_df['PN'])
    pn_dict = dict(zip(word_list, pn_list))
    dict_list = []
    for key,value in  pn_dict.items():
        dict_list.append((key,value))
    try:
        conn = pymssql.connect(server, user, password, database)
        cur = conn.cursor()
        sql = ' insert into report_pn_dictionary (dict_keyword,dict_pn) ' \
              ' values(%s, %s) '
        cur.executemany(sql, dict_list)
        conn.commit()
    except pymssql.Error as ex:
        raise ex
    except Exception as ex:
        raise ex
    finally:
        conn.close()


if __name__=="__main__":
    server = '10.10.2.20'
    user = 'test'
    password = 'test'
    database = 'DBAL'
    insert_report_pn_dictionary(server, user, password, database)

答案 1 :(得分:0)

您正在以一种奇怪的方式转换CSV数据表。最重要的错误是值周围的SQL查询引号(因此,“ Hello”是无效的列错误)。我对代码段进行了重新编码,以便您可以看到每个更改,注释和更新。希望我能帮上忙。祝你好运!

我简化了用zip转换数据的过程,以结合从csv_data列和行创建的List(具有相同长度)的两个实例。

编码为Python 3.6.4

固定查询输出

    INSERT INTO report_pn_dictionary (dict_keyword, dict_pn)  
        VALUES("Hello", "0.9999790000000001") 

带有CSV数据表的SQL插入

import pandas as pd
import pymysql as sql  # using my sql module of choice


def insert_report(file: str, server: str, user: str, password: str, database: str):
    csv_data = pd.read_csv(
            filepath_or_buffer = file,  # changed to filepath_or_buffer
            sep = ':',
            encoding = 'utf-8',
            names = ('Word', 'Reading', 'POS', 'PN')
    )

    # convert columns to 2D array w/ zip & list
    # format [ ["Hello", "0.999979"], ["Another Value", "0.33431"] ]
    values = zip(
            list(csv_data['Word']),
            list(csv_data['PN'])
    )

    try:
        conn = sql.connect(server, user, password, database)
        cur = conn.cursor()
        # for loop to get values (zero based)
        for entry in values:
            query = 'INSERT INTO report_pn_dictionary (dict_keyword, dict_pn)' + \
                    ' VALUES("%s", "%s") ' % (entry[0], entry[1])  # added quotes around %s placeholders
            # execute query
            cur.execute(query)
            # push (commit) changes as if using the batch command 'GO'
            conn.commit()
    except sql.Error as ex:  # Bad >:[
        raise ex
    except Exception as ex:  # Bad. >:[
        raise ex
    finally:  # Meh. :l
        conn.close()


if __name__ == "__main__":
    insert_report(
            file = r'C:\test.csv',
            server = '127.0.0.1',
            user = 'test',
            password = 'test',
            database = 'DBAL'
    )