【问题标题】:data being inserted into MySQL but not made permanent - Python数据被插入 MySQL 但不是永久的 - Python
【发布时间】:2013-08-30 21:22:20
【问题描述】:

我正在使用MySQLdb 来操作MySQL 数据库,并且我有以下例程,将一些数据注入一个名为urls 的表中:

def insert_urls(dbconn, filenames):
    root = "<path>/"
    link = "http://<url>/"
    for f in filenames:
        filename = root + f + ".html"
        local_url = link + f + ".html"
        print(filename, local_url)
        sql = """
        INSERT INTO urls(url, filename) VALUES('%s', '%s');
        """ % (local_url, filename)
        print(sql)
        dbconn.execute_query(sql)

urls 表的声明可在此处找到:

def create_urls_table():

    sql = """
        CREATE TABLE IF NOT EXISTS urls (
            id INT NOT NULL AUTO_INCREMENT,
            url BLOB NOT NULL,
            filename BLOB NOT NULL,
            PRIMARY KEY(id)
        ) ENGINE=INNODB;
    """
    return sql

dbconnDbconn类的对象,定义为:

class Dbconn:
    def __init__(self,
                 host="",
                 user="",
                 pwd="",
                 database=""):

        self.host = host
        self.user = user
        self.pwd = pwd
        self.db = database
        self.cursor = None
        self.conn = None

        try:
            self.conn = MySQLdb.connect(host=self.host,
                                        user=self.user,
                                        passwd =self.pwd,
                                        db=self.db)
            self.cursor = self.conn.cursor()
            print "Connection established"
        except MySQLdb.Error, e:
            print "An error has occurred ", e

    def execute_query(self, sql=""):
        try:
            self.cursor.execute(sql)
        except MySQLdb.Error, e:
            print "An error has occurred ", e

运行程序insert_urls 后,我得到以下输出:

  INSERT INTO urls(url, filename) VALUES ('http://<url>/amazon.html','<path>/amazon.html');
  INSERT INTO urls(url, filename) VALUES('http://<url>/linkedin.html', '<path>/linkedin.html');
  INSERT INTO urls(url, filename) VALUES('http://<url>/nytimes.html', '<path>/nytimes.html');

我可以通过命令行手动注入MySQL。 但是做一个SELECT * FROM urls 查询我什么也没找到。在我手动插入两行后,我得到了:

mysql> select * from urls;
+----+------------------------------------------------+------------------------+
| id | url                                            | filename               |
+----+------------------------------------------------+------------------------+
| 19 | http://<url>/yelp.html                         | <path>/yelp.html       |       
| 29 | http://<url>/amazon.html                       | <path>/amazon.html     |
+----+------------------------------------------------+------------------------+

请注意id 值正在递增...这可能意味着正在插入数据,但没有持久化?有人可以帮我吗?

【问题讨论】:

    标签: python mysql mysql-python


    【解决方案1】:

    在您的execute() 声明之后,致电commit()

    self.cursor.execute(sql)
    self.conn.commit()
    

    欲了解更多信息,请参阅:python mysql insert data

    【讨论】:

    • Traceback(最近一次调用最后):文件“download_page.py”,第 122 行,在 main() 文件“download_page.py”,第 118 行,在 main insert_urls(dbconn, filenames ) 文件“download_page.py”,第 95 行,insert_urls dbconn.execute_query(sql) 文件“C:\performance\Iperf\dbconn.py”,第 127 行,execute_query self.cursor.commit() AttributeError: 'Cursor'对象没有属性“提交”
    • 糟糕,应该是self.conn.commit()。固定。
    【解决方案2】:

    您可能正在使用事务数据库,在这种情况下您必须调用

    self.conn.commit()
    

    (事实上,INNODB 是一个事务型数据库。)


    您可以将commit 合并到execute_query

    def execute_query(self, sql=""):
        try:
            self.cursor.execute(sql)
        except MySQLdb.Error as e:
            print "An error has occurred ", e
            self.conn.rollback()
        else:
            self.conn.commit()
    

    但是,在某些情况下,您可能希望在调用 commitrollback 之前执行多个查询。在这种情况下,您需要从execute_query 中删除commit,并在需要时显式调用commit,或者在退出with 套件时使用上下文管理器调用commit


    请注意,MySQLdb 连接是上下文管理器。你可以写

    connection = MySQLdb.connect(
        host=config.HOST, user=config.USER,
        passwd=config.PASS, db=config.MYDB, )
    
    with connection as cursor:
        cursor.execute(...)
    

    并且连接将在退出with-suite 时调用connection.commit(),如果出现异常则调用connection.rollback()。 这是 MySQLdb.connections.py 中控制它的代码:

    def __enter__(self): return self.cursor()
    
    def __exit__(self, exc, value, tb):
        if exc:
            self.rollback()
        else:
            self.commit()
    

    【讨论】:

      猜你喜欢
      • 2018-02-06
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多