我使用python 3.9插入多个新闻列表从谷歌rss新闻到SQL表参数使用pyobc,但总是得到编程错误下面:
cursor.execute pyodbc(查询)。ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server] 'cò'附近语法错误。(102) (SQLExecDirectW)")
我检查了sql表,发现实际上一些记录已经导入到sql成功(15条记录),但不是所有的(30条记录)
下面是我所有的代码,请帮忙!
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我试图提取到txt文件,它完全工作正常
正如@PanagiotisKanavos所评论的,使用行业推荐的SQL参数化最佳实践,它超越了Python和SQL Server,但任何应用层代码和任何SQL兼容的数据库。
这个方法不仅可以安全地转义用户提交的值,还可以避免特殊字符的破坏,例如大小写中的重音符号,甚至字符串中的引号。此外,还可以增强代码的可读性、可维护性和效率。甚至考虑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()
在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')