【问题标题】:MySQL ProgrammingError 1064, dealing with raw dataMySQL ProgrammingError 1064,处理原始数据
【发布时间】:2020-11-27 05:57:27
【问题描述】:

我正在尝试将我的数据插入到我已经创建的数据库中。我已将架构提供给 db,因此它接受 varchar 和 text 用于适当的列,并接受 date/integer 用于其他两个。我能够连接到我的数据库,但我正在与错误消息作斗争,并且我的代码根据我的格式继续失败。如果有人可以指导如何改变这种情况,我将不胜感激! (我已经注释掉了try/error,只是为了在运行代码时得到错误信息输出。)

   #open db connection
    db = mysql.connector.connect(host='localhost', user='root', database='WebScraping')
    print(db)
    #prepare a cursor object using cursor() method
    cursor = db.cursor()
    #prepare SQL query to INSERT a record into the database
    sql = "INSERT INTO WebScraping.Reviews(name, location, date, rating, content) VALUES ('{}', '{}', '{}', '{}', '{}')".format(name, location, date, rating, content)
   #try:
        #execute the SQL command
    cursor.execute(sql)
   #commit your changes in the database
    db.commit()
    print("Record committed")
    #except:
        #Rollback if there is an error
        #db.rollback()
    #disconnect from the server
    cursor.close()
    db.close()

【问题讨论】:

    标签: mysql mysql-python mysql-error-1064


    【解决方案1】:

    不要使用字符串格式,使用查询参数。

    sql = """INSERT INTO WebScraping.Reviews(name, location, date, rating, content) 
             VALUES (%s, %s, %s, %s, %s)"""
    cursor.execute(sql, (name, location, date, rating, content))
    

    如果date 的格式为mm/dd/yyyy,则需要使用STR_TO_DATE() 对其进行解析。

    sql = """INSERT INTO WebScraping.Reviews(name, location, date, rating, content) 
             VALUES (%s, %s, STR_TO_DATE(%s, '%m/%d/%Y'), %s, %s)"""
    

    【讨论】:

    • 谢谢!我已经尝试过——现在我得到一个响应,结果 = self._cmysql.convert_to_mysql(params)——InterfaceError: Python 类型无法转换。这是我的 mysql 数据错误还是我在 py 代码中的语法。请原谅这些愚蠢的问题,我是编码世界的新手,并试图尽可能地学习和理解。
    • 这听起来像是数据错误。 content的类型是什么?
    • 我以字符串的形式输入前 3 个文本,然后是日期(尽管格式为 mm/dd/yyyy)。和一个评级(整数,已在我的脚本中转换)。最后,内容也是我在表格中作为“文本”输入的一串文本。
    • 编辑问题并添加完整的回溯。也许它会有足够的信息来知道是哪个参数导致了问题。
    • MySQL 希望日期格式为yyyy-mm-dd
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 2011-07-18
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多