简体   繁体   English

使用Python的DB-API

[英]DB-API with Python

I'm trying to insert some data into a local MySQL database by using MySQL Connector/Python -- apparently the only way to integrate MySQL into Python 3 without breaking out the C Compiler. 我正在尝试使用MySQL Connector / Python将一些数据插入本地MySQL数据库中-这显然是在不破坏C编译器的情况下将MySQL集成到Python 3中的唯一方法。

I tried all the examples that come with the package; 我尝试了该软件包随附的所有示例; Those who execute can enter data just fine. 执行的人员可以输入数据。 Unfortunately my attempts to write anything into my tables fail. 不幸的是,我尝试将任何内容写入表的尝试都失败了。

Here is my code: 这是我的代码:

import mysql.connector


def main(config):
    db = mysql.connector.Connect(**config)
    cursor = db.cursor()

    stmt_drop = "DROP TABLE IF EXISTS urls"
    cursor.execute(stmt_drop)

    stmt_create = """
    CREATE TABLE urls (
        id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
        str VARCHAR(50) DEFAULT '' NOT NULL,
        PRIMARY KEY (id)
    ) CHARACTER SET 'utf8'"""
    cursor.execute(stmt_create)

    cursor.execute ("""
        INSERT INTO urls (str)
        VALUES
        ('reptile'),
        ('amphibian'),
        ('fish'),
        ('mammal')
        """)
    print("Number of rows inserted: %d" % cursor.rowcount)
    db.close()
if __name__ == '__main__':
    import config
    config = config.Config.dbinfo().copy()
    main(config)

OUTPUT: 输出:

Number of rows inserted: 4 插入的行数:4

I orientate my code strictly on what was given to me in the examples and can't, for the life of mine, figure out what the problem is. 我严格按照示例中给出的内容来定向我的代码,并且在我的生命中无法确定问题出在哪里。 What am I doing wrong here? 我在这里做错了什么?

Fetching table data with the script works just fine so I am not worried about the configuration files. 使用脚本获取表数据可以很好地工作,因此我不必担心配置文件。 I'm root on the database so rights shouldn't be a problem either. 我基于数据库,因此权限也不应该成为问题。

您需要添加db.commit()来提交更改,然后再使用db.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM