用Python进行MySQL操作


=Start=

缘由:

最近在复习Python的相关知识时碰到的老问题的新解法,觉得可以记录一下。

参考解答:
Python Database API
MySQLdb的安装(在MySQL Server为Percona的情况下)
$ wget https://pypi.python.org/packages/source/M/MySQL-python/MySQL-python-1.2.5.zip
$ unzip MySQL-python-1.2.5.zip
$ cd MySQL-python-1.2.5
$ sudo /usr/local/bin/python setup.py install
...
EnvironmentError: mysql_config not found
...

$ history | grep -i 'Percona-Server'
sudo yum install Percona-Server-server-55.x86_64 percona-toolkit

$ sudo yum install Percona-Server-devel-55.x86_64
$ sudo find /usr -type f -iname "mysql_config"
$ sudo /usr/local/bin/python setup.py install
#!/usr/bin/env python
# coding=utf-8

import MySQLdb

class MysqlDB(object):
    def __init__(self, host='127.0.0.1', port=3306, user='', passwd=''):
        self.conn = MySQLdb.connect(host=host, port=port, user=user, passwd=passwd, charset='utf8')
        self.cur = self.conn.cursor()

    def query(self, sql_str):
        ret_tuple = None
        try:
            self.cur.execute(sql_str)
            ret_tuple = self.cur.fetchall()
            self.conn.commit()
        except MySQLdb.Error as e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
        return ret_tuple

    def safe_query(self, mode, param_tuple):
        ret_tuple = None
        try:
            self.cur.execute(mode, param_tuple)
            ret_tuple = self.cur.fetchall()
            self.conn.commit()
        except MySQLdb.Error as e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
        return ret_tuple

    def update(self, sql_str):
        try:
            self.cur.execute(sql_str)
            self.conn.commit()
        except MySQLdb.Error as e:
            self.conn.rollback()
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])

    def safe_update(self, mode, param_tuple):
        try:
            self.cur.execute(mode, param_tuple)
            self.conn.commit()
        except MySQLdb.Error as e:
            self.conn.rollback()
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
MySQL官方也推出了Python版的Connector

=EOF=


《“用Python进行MySQL操作”》 有 10 条评论

  1. 在进行敏感操作之前,一个比较好的习惯就是——提前备份,这也同样适用于MySQL操作。
    在测试过程中谁也说不清楚可能会发生什么情况,所以,先备份以防万一总是没错的,下面记录一下如何备份MySQL数据库中的表内容及索引:
    `
    #复制内容、索引
    CREATE TABLE new_table LIKE old_table;
    INSERT new_table SELECT * FROM old_table;
    #只复制内容,不复制索引、触发器
    CREATE TABLE new_table AS SELECT * FROM old_table;
    `
    http://stackoverflow.com/questions/3280006/duplicating-a-mysql-table-indexes-and-data

  2. 在用MySQLdb的时候,可能会出现「No database selected」的错误,处理办法有2个:
    `
    OperationalError: (1046, ‘No database selected’)

    方法一:
    如果不存在跨数据库操作的话,可以在connect的时候就指定好数据库名称(db=xxx),比如:
    MySQLdb.connect(host=”localhost”, user=”joebob”, passwd=”moonpie”, db=”thangs”)

    方法二:
    在每一个要操作的table名称前面添加上所在数据库的名称,避免出现上述报错。
    `
    http://mysql-python.sourceforge.net/MySQLdb.html
    https://foofish.net/python-mysql.html

  3. Python:出现ValueError: unsupported format character的解决办法
    https://www.polarxiong.com/archives/Python-%E5%87%BA%E7%8E%B0ValueError-unsupported-format-character%E7%9A%84%E8%A7%A3%E5%86%B3%E5%8A%9E%E6%B3%95.html
    `
    出现这种错误一般是在Python中写其他语言的代码,比如MySQL中:
    db.execute(“SELECT DATE_FORMAT(snapdate,’%Y-%m-%d’) AS date FROM table1)

    此时,%在字符串中作为格式化字符串的关键字,当其后为诸如n、c、s时进行正常转义;而出现上述代码时即返回错误。

    解决方法:
    一、使用%%,即表示非关键字的%(推荐);
    二、使用\%,有些情况下适用。
    `

  4. InterfaceError (0, ”)
    https://stackoverflow.com/questions/6650940/interfaceerror-0
    `
    This is caused by a global cursor. Try creating and closing the cursor within each method a raw query is needed.
    这是由全局cursor引起的。尝试在需要查询的每个方法中动态创建和关闭cursor。
    `
    Python MySQLdb模块中的ping()
    https://www.cnblogs.com/bugmaker/articles/2444905.html
    `
    mysql连接如果长时间idle的话,(时间:默认为8小时),会自动断开,而且不会为原连接自动恢复。
    解决办法:比较ugly
    在每次连接之前,判断该链接是否有效。或者在每次数据库操作的时候动态 conn/execute/close 。
    `

  5. 数据库连接池,本地线程,上下文管理
    https://www.cnblogs.com/huchong/p/8229075.html
    `
    一、数据库连接池
    1.链接池原理
    2.不使用连接池链接数据库
    方式一:每次操作都要链接数据库,链接次数过多
    方式二:不支持并发
    3.基于DButils实现的数据库连接池
    模式一
    模式二(推荐)
    二、本地线程
    三、上下文管理
    1. 上下文原理
    2. Flask内部实现
    `

    https://pypi.org/project/DBUtils/

    Python 数据库连接池DButils
    https://www.cnblogs.com/ctztake/p/8213951.html

回复 hi 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注