简体   繁体   English

使用Python将数据插入SQL Server(3.7.4)

[英]Insert data to SQL Server with Python (3.7.4)

I am trying to insert data to my table in Microsoft SQL Server using a Python script. 我正在尝试使用Python脚本在Microsoft SQL Server中的表中插入数据。

Initially I am trying to upload an excel file, but got error messages and have tried to lesser the scale of the task. 最初,我尝试上传excel文件,但收到错误消息,并尝试减小任务的规模。 At this point I am trying to push some data trough to an already existing table in my database. 在这一点上,我试图将一些数据槽推入数据库中已经存在的表中。 In this example my servername is SERVERNAME, database is DATABASENAME and my table is TABLE. 在此示例中,我的服务器名是SERVERNAME,数据库是DATABASENAME,我的表是TABLE。 The script is: 脚本是:

import pyodbc 
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=SERVERNAME;'
                      'Database=DATABASENAME;'
                      'Trusted_Connection=yes;')

cursor = conn.cursor()
cursor.execute('INSERT INTO DATABASENAME.dbo.TABLE(Name, Age, City)
VALUES ('Alan', '30', 'London');

for row in cursor:
    print(row)

I get this error message: 我收到此错误消息:

Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    exec(open("C:\\pandasql.py").read())
  File "<string>", line 9
    cursor.execute('INSERT INTO DATABASENAME.dbo.TABLE (Name, Age, City)
                                                                       ^
SyntaxError: EOL while scanning string literal

I want the one row with data to be seen in my database. 我希望在数据库中看到包含数据的一行。 What am I doing wrong? 我究竟做错了什么?

If you want to use single quotes within a single-quote string you need to escape them by adding a \\ before them - or using a double-quote string. 如果要在单引号字符串中使用单引号,则需要通过在单引号之前添加\\或使用双引号字符串来对其进行转义。

Example: 例:

import pyodbc 
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=SERVERNAME;'
                      'Database=DATABASENAME;'
                      'Trusted_Connection=yes;')

cursor = conn.cursor()
cursor.execute("INSERT INTO DATABASENAME.dbo.TABLE(Name, Age, City) VALUES ('Alan', '30', 'London')")

If you want your changes to be saved to the database, you also need to call commit on the connection or set autocommit to True : 如果要将更改保存到数据库,则还需要在连接上调用commit或将autocommit设置为True

# either enable autocommit
conn = pyodbc.connect('...CONNECTION STRING...', autocommit=True)

# or after inserting the row:
conn.commit()

If you want to retrieve the resulting row, you need to select it first, eg: 如果要检索结果行,则需要首先选择它,例如:

cursor.execute("SELECT * FROM DATABASENAME.dbo.TABLE")
for row in cursor:
    print(row)

or use an OUTPUT clause on your INSERT statement: 或在INSERT语句上使用OUTPUT clause

cursor.execute("""
  INSERT INTO DATABASENAME.dbo.TABLE(Name, Age, City)
  OUTPUT Inserted.Name, Inserted.Age, Inserted.City
  VALUES ('Alan', '30', 'London')
""")

for row in cursor:
    print(row)

Full example for your code snippet: 您的代码段的完整示例:

import pyodbc 
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=SERVERNAME;'
                      'Database=DATABASENAME;'
                      'Trusted_Connection=yes;')

cursor = conn.cursor()
cursor.execute("""
  INSERT INTO DATABASENAME.dbo.TABLE(Name, Age, City)
  OUTPUT Inserted.Name, Inserted.Age, Inserted.City
  VALUES ('Alan', '30', 'London')
""")
for row in cursor:
    print(row)

conn.commit()

The colors in the snippet should already show you the problem: you are using a single quote to begin the string and end your string somewhere in between through using another single quote. 代码段中的颜色应该已经向您显示了问题:您正在使用单引号将字符串开头,并在字符串之间通过使用另一单引号结束字符串。

A simple way would be to escape that qoute (through adding a \\ in front); 一种简单的方法是转义该qoute(通过在前面添加\\ ); a better way that also helps to secure your code against SQL injection would be to use prepared statements 一种更好的方式(也可以帮助确保您的代码免遭SQL注入)是使用准备好的语句

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

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