1. 程式人生 > 其它 >【mysqlclient】python3基於mysqlclient封裝的資料庫增刪改查操作

【mysqlclient】python3基於mysqlclient封裝的資料庫增刪改查操作

1. 官網

http://mysql-python.sourceforge.net/MySQLdb.html

 

2. github地址

python2

https://github.com/farcepest/MySQLdb1

python3

https://github.com/PyMySQL/mysqlclient

 

3. pypi

https://pypi.python.org/pypi/MySQL-python/1.2.5

https://pypi.python.org/pypi/mysqlclient/

 

4. 安裝

python2

pip install MySQL-python==1.2.5

python3

pip install
mysqlclient

另一種方式就是原始碼安裝

 

 

5. mysql-client封裝示例

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

import logging
import MySQLdb

from MySQLdb import cursors


class MySQLdbUtil(object):

    def __init__(self, host, user, passwd, db, port):
        self.host = host
        self.user = user
        self.passwd 
= passwd self.db = db self.port = port self.cursor = None self.conn = None def get_connection(self): self.conn = MySQLdb.connect(self.host, self.user, self.passwd, self.db, self.port) def select_one(self, sql): try: self.get_connection() self.cursor
= self.conn.cursor(cursors.DictCursor) self.cursor.execute(sql) self.conn.commit() data = self.cursor.fetchone() return data except Exception as e: logging.error(e) self.conn.rollback() finally: self.close() def select_many(self, sql): try: self.get_connection() self.cursor = self.conn.cursor(cursors.DictCursor) self.cursor.execute(sql) self.conn.commit() data = self.cursor.fetchall() return data except Exception as e: logging.error(e) self.conn.rollback() finally: self.close() def delete_operation(self, sql): try: self.get_connection() cursor = self.conn.cursor() count = cursor.execute(sql) self.conn.commit() return count except Exception as e: logging.error(e) self.conn.rollback() finally: self.close() def update_operation(self, sql): try: self.get_connection() cursor = self.conn.cursor() count = cursor.execute(sql) self.conn.commit() return count except Exception as e: logging.error(e) self.conn.rollback() finally: self.close() def insert_operation(self, sql): try: self.get_connection() cursor = self.conn.cursor() count = cursor.execute(sql) self.conn.commit() return count except Exception as e: logging.error(e) self.conn.rollback() finally: self.close() def close(self): self.cursor.close() self.conn.close() if __name__ == '__main__': client = MySQLdbUtil("192.168.x.xxx", "root", "xxxxx", "test", 3306) result = client.select_many("select * from role;") print(result)

 

6. MySQLdb示例

https://zhuanlan.zhihu.com/p/25539328

 

7. 關於cursor

 

相關介紹

https://www.cnblogs.com/fireblackman/p/16014467.html 

 

參考連結:

https://sourceforge.net/projects/mysql-python/files/

https://mysqlclient.readthedocs.io/

https://www.runoob.com/python/python-mysql.html