[英]pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near
I'm using python 3.9 to insert a list of multiple news from google rss news to SQL table with parameter using pyobc but always getting programming error below:我正在使用 python 3.9 将多个新闻的列表从 google rss 新闻插入到 SQL 表,其中参数使用 pyobc 但总是出现以下编程错误:
cursor.execute(query) pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'cò'. (102) (SQLExecDirectW)")
cursor.execute(query) pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL 服务器驱动程序][SQL Server] 'cò' 附近语法不正确。(102) (SQLExecDirectW)"
I checked the sql table and found out actually some of records had been imported to SQL successfully (15 records ) but not all of its (30 records)我检查了 sql 表,发现实际上一些记录已成功导入到 SQL(15 条记录)但不是全部(30 条记录)
Below its all of my codes pls help !在我所有的代码下面请帮忙!
import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen
import pyodbc
news_url="https://news.google.com/rss?hl=vi&gl=VN&ceid=VN:vi"
Client=urlopen(news_url)
xml_page=Client.read()
Client.close()
soup_page=soup(xml_page,"xml")
news_list=soup_page.findAll("item")
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=ADMIN;DATABASE=NewsCollect2')
cursor = cnxn.cursor()
for news in news_list:
query = f"insert into news2(Title,Source1,Time1) values (N'"+news.title.text+"',N'"+news.source.text+"',N'"+news.pubDate.text+"')"
cursor.execute(query)
cursor.commit()
cursor.close()
cnxn.close()
p/s I tried to extract to txt file and it worked totally fine p/s 我试图提取到 txt 文件并且它工作得很好
in python3, you need to add two lines after your conn在 python3 中,您需要在 conn 之后添加两行
import pyodbc as db # forgot the imports
conn = pyodbc.connect(driver=driver, server=serv, database=db,port = prt,
uid=usr, pwd=passwd)
conn.setdecoding(db.SQL_CHAR, encoding='latin1')
conn.setencoding('latin1')
As commented by @PanagiotisKanavos, use the industry recommended best practice of SQL parameterization which goes beyond Python and SQL Server but any application layer code and any SQL-compliant database.正如@PanagiotisKanavos 评论的那样,使用行业推荐的 SQL 参数化最佳实践,该实践超出了 Python 和 SQL任何符合应用程序层的数据库和 SQL 服务器的代码。
Not only does this method safely escape user-submitted values, you also avoid breakage with special characters such as accent marks per your case and even quotes within the strings.此方法不仅可以安全地转义用户提交的值,还可以避免特殊字符的损坏,例如每个案例的重音符号,甚至字符串中的引号。 Additionally, you enhance code readability, maintainability, and arguably efficiency.
此外,您还增强了代码的可读性、可维护性和可以说的效率。 Even consider
executemany
:甚至考虑
executemany
:
# PREPARED STATEMENT (NO DATA)
query = "insert into news2 (Title, Source1, Time1) values (?, ?, ?)"
# LIST OF TUPLES FOR PARAMS
data = [(news.title.text, news.source.text, news.pubDate.text) for news in newslist]
# EXECUTE STATEMENT AND BIND PARAMS
cursor.executemany(query, data)
cursor.commit()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.