数据被插入MySQL但不是永久性的 - Python

时间:2013-08-27 23:34:17

标签: python mysql mysql-python

我正在使用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

dbconn是类Dbconn的对象,定义为:

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值正在递增...这可能意味着数据正在插入,但不会持续存在?有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:4)

您可能正在使用交易数据库,在这种情况下您必须致电

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之前,您可能希望执行大量查询。在这种情况下,您需要从commit中删除execute_query,并在需要时显式调用commit,或在退出{{1时使用上下文管理器调用commit }} - 套件


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

MySQLdb

,如果出现异常,连接会在退出connection = MySQLdb.connect( host=config.HOST, user=config.USER, passwd=config.PASS, db=config.MYDB, ) with connection as cursor: cursor.execute(...) 时调用connection.commit(),或with-suite。 以下是在MySQLdb.connections.py中控制它的代码:

connection.rollback()

答案 1 :(得分:1)

execute()语句后,请致电commit()

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

有关详细信息,请参阅:python mysql insert data