简体   繁体   English

如何使用 python 将列表数据传递到 SQL 服务器中的插入语句?

[英]How to pass list data into insert statement in SQL server using python?

I'm new to python and creating a python app to insert data into the SQL server table.我是 python 的新手,正在创建一个 python 应用程序以将数据插入到 SQL 服务器表中。 I'm trying it in the following way but it gives me an error.我正在通过以下方式尝试它,但它给了我一个错误。

This is my code这是我的代码

import pyodbc

conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=.\SQLEXPRESS;'
                      'Database=company_mine;'
                      'Trusted_Connection=yes;')

datalist = ['KFC', ' kfc', '71 Tottenham Ct Rd', 'London', 'null', 'null', 'London']

sql_insert_query1 = """INSERT INTO company_details(company_name,contact_name,mailing_street,mailing_city,mailing_state,mailing_postal_code,mailing_country)VALUES(%s)"""

cursor1 = conn.cursor()
cursor1.executemany(sql_insert_query1, datalist)
conn.commit()
print(cursor1.rowcount, "Record inserted successfully")

这是错误

Please help me to solve this problem.请帮我解决这个问题。

It seems you only want to insert a single row in your table.您似乎只想在表中插入一行。 In that case, try replacing the line在这种情况下,请尝试更换该行

cursor1.executemany(sql_insert_query1, datalist)

with

cursor1.execute(sql_insert_query1, datalist)

cursor1.executemany expects to be given a list of lists of values, and will execute the statement it has been given once for each list in the list of lists. cursor1.executemany期望得到一个值列表的列表,并将对列表列表中的每个列表执行一次给它的语句。 For example, if you had two rows to insert, your datalist variable might look like the following (I've made up details for the second row):例如,如果您要插入两行,则您的datalist变量可能如下所示(我已经为第二行编写了详细信息):

datalist = [
    ['KFC', ' kfc', '71 Tottenham Ct Rd', 'London', 'null', 'null', 'London'],
    ['LGN', ' lgn', '72 High Street', 'Birmingham', 'null', 'null', 'Birmingham']
]

If you passed this to cursor.executemany , it would run two INSERT statements, one using the values in the first list within datalist , and one using the values in the second list.如果将其传递给cursor.executemany ,它将运行两个INSERT语句,一个使用datalist中第一个列表中的值,一个使用第二个列表中的值。


I've noticed another couple of problems with your code.我注意到您的代码还有另外几个问题。 Firstly, the SQL statement in sql_insert_query1 contains only a single %s placeholder.首先,sql_insert_query1 中的sql_insert_query1语句仅包含一个%s占位符。 You need to have one for each column.每列都需要一个。 You have seven columns, so replace VALUES(%s) with VALUES(%s,%s,%s,%s,%s,%s,%s) .您有七列,因此将VALUES(%s)替换为VALUES(%s,%s,%s,%s,%s,%s,%s)

Also, I note that you are attempting to insert the string 'null' into some of the above columns.另外,我注意到您正试图将字符串'null'插入到上述某些列中。 This won't insert a SQL NULL value, instead, it will insert the text null into that column, which you might not want.这不会插入 SQL NULL值,而是会将文本null插入该列,您可能不需要。 Use the Python None value to represent a SQL NULL value.使用 Python None值表示 SQL NULL值。

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

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