DPS*_*ial 5 python postgresql psycopg2
基于几个例子(这里,这里),我可以使用 psycopg2 读取并希望从 python 运行 SQL 文件(该文件有 200 行,虽然运行速度很快,但不是我想在 python 文件中维护的内容) 。
\n\n这是读取和运行该文件的脚本:
\n\nsql = open("sql/sm_bounds_current.sql", "r").read()\n\ncurDest.execute(sql)\nRun Code Online (Sandbox Code Playgroud)\n\n但是,当我运行脚本时,会引发以下错误:
\n\nError: syntax error at or near "\xc3\xaf\xc2\xbb\xc2\xbfdrop"\nLINE 1: \xc3\xaf\xc2\xbb\xc2\xbfdrop table dpsdata.sm_boundaries_current_dev;\nRun Code Online (Sandbox Code Playgroud)\n\n正如您所看到的,脚本中的第一行是删除一个表,但我不确定为什么要读取额外的字符,并且似乎找不到可能设置文件编码的解决方案阅读时。
\n发现这篇文章涉及编码和字节顺序标记,这就是我的问题所在。
解决方案是从 CODECS 导入 OPEN,这允许在 OPEN 上使用 ENCODING 选项:
import codecs
from codecs import open
sqlfile = "sql/sm_bounds_current.sql"
sql = open(sqlfile, mode='r', encoding='utf-8-sig').read()
curDest.execute(sql)
Run Code Online (Sandbox Code Playgroud)
看起来效果很好!
| 归档时间: |
|
| 查看次数: |
18420 次 |
| 最近记录: |