资讯专栏INFORMATION COLUMN

Python 连接 MySQL

williamwen1986 / 1565人阅读

摘要:一普通连接方法使用模块普通方式连接。返回结果表示影响的行数。查询时不需要操作,插入更新删除时需要提交。模块点此下载类继承自,表示一个新的连接池。如果需要新的连接池,按照如下格式新增即可。一个连接池可同时提供多个实例对象。

一、普通 MySQL 连接方法

  使用模块 MySQLdb 普通方式连接。

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

import MySQLdb

conn = MySQLdb.connect(host="127.0.0.1", port=3306, user="root", passwd="123", db="test")
cursor = conn.cursor()

sql_1 = "select * from user where id = %s;" % (5,)
sql_2 = "select * from user 
         where id = %s;" % (5,)
sql_3 = """
           insert into user(username, password)
           values("yuchaoshui", "123");
        """

try:
    print cursor.execute(sql_1)
    print cursor.fetchall()

    print cursor.execute(sql_2)
    print cursor.fetchall()

    print cursor.execute(sql_3)
    conn.commit()

except Exception as e:
    print(e)
    conn.rollback()

cursor.close()
conn.close()

   execute() 返回结果表示影响的行数。cursor.fetchone() 取回一条结果。sql_1 直接一行写完,sql_2 换行写完, sql_3 多行写。 查询时不需要 commit() 操作,插入、更新、删除时需要 commit() 提交。

二、使用连接池连接MySQL
#!/usr/bin/env python
# _*_ coding:utf-8 _*_

import MySQLdb
from DBUtils.PooledDB import PooledDB

pool = PooledDB(MySQLdb, 5, host="127.0.0.1", port=3306, user="root", passwd="123", db="test")
conn = pool.connection()
cursor = conn.cursor()

sql_1 = "select * from user where id = %s;" % (5,)
sql_2 = "select * from user 
         where id = %s;" % (5,)
sql_3 = """
           insert into user(username, password)
           values("yuchaoshui", "123");
        """
try:
    print cursor.execute(sql_1)
    print cursor.fetchall()

    print cursor.execute(sql_2)
    print cursor.fetchall()

    print cursor.execute(sql_3)
    conn.commit()

except Exception as e:
    print(e)
    conn.rollback()

cursor.close()
conn.close()

   5 为连接池里的最少连接数, 以后每次需要数据库连接就是用connection()函数获取连接就好了

PooledDB 的默认值

PooledDB(self, creator, mincached=0, maxcached=0, maxshared=0, maxconnections=0, blocking=False, maxusage=None, setsession=None, reset=True, failures=None, ping=1, *args, **kwargs)

PooledDB的参数:

mincached,最少的空闲连接数,如果空闲连接数小于这个数,pool会创建一个新的连接

maxcached,最大的空闲连接数,如果空闲连接数大于这个数,pool会关闭空闲连接

maxconnections,最大的连接数,

blocking,当连接数达到最大的连接数时,在请求连接的时候,如果这个值是True,请求连接的程序会一直等待,直到当前连接数小于最大连接数,如果这个值是False,会报错,

maxshared , 当连接数达到这个数,新请求的连接会分享已经分配出去的连接


三、模块导入连接 MySQL

  以连接池的方式,编写模块 mysqlhelper.py,可以在项目的其他地方导入MySQL连接实例即可使用。 模块点此下载 mysqlhelper.py

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

from __future__ import print_function
from DBUtils.PooledDB import PooledDB
import MySQLdb
import sys

__all__ = ["m"] + ["m"+str(i) for i in range(2, 11)]

class MH(object):
    def __init__(self):
        try:
            print("Connecting MySQL Server {0}@{1}:{2} ..".format(
                self.__class__.db, self.__class__.host, self.__class__.port), end=".")

            self.conn = self.__class__.pool.connection()
            self.cursor = self.conn.cursor()
            print(" ok!")
        except Exception, e:
            print("pool.connection error: {0}".format(e))

    def select(self, query=""):
        try:
            self.effect = self.cursor.execute(query)
            return self.cursor
        except Exception as e:
            print("select error: {0}".format(e))

    def update(self, query=""):
        try:
            self.effect = self.cursor.execute(query)
            self.conn.commit()
        except Exception as e:
            print("update error: {0}".format(e))
            self.conn.rollback()
            self.effect = 0


# M2 类继承自 M1,表示一个新的 MySQL 连接池。
# 如果需要新的连接池 ,按照如下格式新增即可。
class MH2(MH):
    pass


def init_pool(M,
            host="127.0.0.1", 
            port=3306, 
            user="root", 
            password="", 
            database="test",
            pool_size=5): 

    M.host = host
    M.port = int(port)
    M.user = user
    M.password = password
    M.db = database
    M.pool_size = pool_size
    try:
        M.pool = PooledDB(MySQLdb, 
            M.pool_size,
            host=M.host,
            port=M.port,
            user=M.user,
            passwd=M.password,
            db=M.db)
    except Exception, e:
        print("PooledDB init error: {0}".format(e))
        exit(1)


# 初始化连接池,可以有多个。第一个参数是前面手动定义的连接池类。
init_pool(MH, "127.0.0.1", 3306, "root", "123", "test")
init_pool(MH2, "12.55.5.61", 3306, "root", "123", "test")


# 定义将要被导出的MySQL实例。 一个连接池可同时提供多个实例对象。
m = MH()
m2 = MH2()


if __name__ == "__main__":
    pass
    #print "
m info:"
    #print m.select("select * from user;").fetchone()
    #print m.effect
    #print m.select("select * from user;").fetchall()
    #print m.effect
    #m.update("insert into user(username,password) values("haha", "heihei");")
    #print m.effect
    ##################################################
    #print "
m2 info:"
    #print m2.select("select * from user;").fetchone()
    #print m2.effect
    #print m2.select("select * from user;").fetchall()
    #print m2.effect
    #m2.update("insert into user(username,password) values("haha", "heihei");")
    #print m2.effect


使用方法

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

from mysqlhelper import m, m2
import time

def test():
    print "
m info:"
    print m.select("select * from user;").fetchone()
    print m.effect
    print m.select("select * from user;").fetchall()
    print m.effect
    m.update("insert into user(username,password) values("haha", "heihei");")
    print m.effect
    
    #################################################
    
    print "
m2 info:"
    print m2.select("select * from user;").fetchone()
    print m2.effect
    print m2.select("select * from user;").fetchall()
    print m2.effect
    m2.update("insert into user(username,password) values("haha", "heihei");")
    print m2.effect

if __name__ == "__main__":
    test()



文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/44588.html

相关文章

  • python 数据库编程,这篇是针对 mysql 的,滚雪球学Python第4季第13篇

    摘要:的安装博客补充知识年最新安装教程,滚雪球学第四季。操作操作数据库一般被程序员成为操作增删改查,其中各个字符分别代表新增,读取,更新,删除。可以返回受影响行数,可以直接通过该值判断是否修改成功。 ...

    xiaowugui666 评论0 收藏0
  • Python 中的 MySQL 数据库连接

    摘要:说多了都是泪,我之前排查内存泄漏的问题,超高并发的程序跑了个月后就崩溃。以前写中间件的时候,就总是把用户当,要尽量考虑各种情况避免内存泄漏。 从 Java 到 Python 本文为我和同事的共同研究成果 当跨语言的时候,有些东西在一门语言中很常见,但到了另一门语言中可能会很少见。 例如 C# 中,经常会关注拆箱装箱,但到了 Java 中却发现,根本没人关注这个。 后来才知道,原来是因为...

    Paul_King 评论0 收藏0
  • Python之使用Pandas库实现MySQL数据库的读写

    摘要:本次分享将介绍如何在中使用库实现数据库的读写。提供了工具包及对象关系映射工具,使用许可证发行。模块实现了与不同数据库的连接,而模块则使得能够操作数据库。   本次分享将介绍如何在Python中使用Pandas库实现MySQL数据库的读写。首先我们需要了解点ORM方面的知识。 ORM技术   对象关系映射技术,即ORM(Object-Relational Mapping)技术,指的是把关...

    darcrand 评论0 收藏0

发表评论

0条评论

williamwen1986

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<