Python使用mysql.connector创建数据库触发SQL1064语法错误如何解决
错误产生原因
- 该1064语法报错是因为你执行的SQL语句
show database不符合MySQL语法规范。MySQL中查询所有已存在数据库的语句要求database使用复数形式,正确的语法为SHOW DATABASES,单数写法会触发语法解析错误。
解决方案
- 直接修正对应SQL语句即可,将代码中
dbcursor.execute("show database")替换为dbcursor.execute("show databases") - 可选优化:创建数据库时建议加上
IF NOT EXISTS判断,避免重复运行代码时触发「数据库已存在」的报错,优化后的创建语句为dbcursor.execute("create database if not exists films")
修正后的完整代码如下:
import mysql.connector db=mysql.connector.connect(host="localhost",user="root",password="PP1994an!") dbcursor=db.cursor() # 新增判断避免重复创建报错 dbcursor.execute("create database if not exists films") # 修正为复数形式的databases dbcursor.execute("show databases") for i in dbcursor: print(i)
内容的提问来源于stack exchange,提问作者Pradyumna Pradhan
相关产品推荐
相关产品推荐

