我正在尝试通过Python运行SQL脚本(db.sql
)。不幸的是,我在执行时遇到SQL错误:
#1064 - You have an error in your SQL syntax...
但是当我将失败的SQL查询复制到Navicat或Sequel Pro之类的SQL应用程序中时,它会按预期执行-没有任何错误。
我正在通过pymysql
连接到SQL。
db.sql 看起来像这样:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `dta_humidity`;
CREATE TABLE `dta_humidity` (
`humi_ID` int(16) NOT NULL AUTO_INCREMENT,
`sensor_ID` int(16) DEFAULT NULL,
`location` varchar(64) DEFAULT NULL,
`humidity` float(3,0) DEFAULT NULL,
`timestamp` int(10) DEFAULT NULL,
`error` int(1) DEFAULT NULL,
PRIMARY KEY (`humi_ID`),
UNIQUE KEY `dta_humidity_humi_ID_uindex` (`humi_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='This table contains all measured humidity data.';
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
app.py ,它执行SQL脚本,如下所示:
import textwrap
def create_query(sql_full_path):
with open(sql_full_path, 'r') as f_in:
lines = f_in.read()
lines.strip()
lines = lines.replace('\r', '').replace('\n', ' ')
lines = lines.replace(' ', ' ')
# Remove leading whitespace from every line
query_string = textwrap.dedent("""{}""".format(lines))
return query_string
query = create_query('config/db.sql')
运行 app.py 时,出现上述错误。我确实将查询输出到终端,看起来像这样:
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; DROP TABLE IF EXISTS `dta_humidity`; CREATE TABLE `dta_humidity` ( `humi_ID` int(16) NOT NULL AUTO_INCREMENT, `sensor_ID` int(16) DEFAULT NULL, `location` varchar(64) DEFAULT NULL, `humidity` float(3,0) DEFAULT NULL, `timestamp` int(10) DEFAULT NULL, `error` int(1) DEFAULT NULL, PRIMARY KEY (`humi_ID`), UNIQUE KEY `dta_humidity_humi_ID_uindex` (`humi_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='This table contains all measured humidity data.';
当我将其复制并在Sequel Pro中执行时,查询正在按预期的方式工作。有什么可以解释这种行为的吗?