您的位置:首页 > 编程语言 > Python开发

【原创】python mysql-connec…

2017-03-20 14:47 369 查看
Python
操作mysql包有MySQLdb、SQLAlchemy等等、还有一个是mysql.connector,mysql官方包,详见(MySQL Connector/Python Developer Guide)。
用法官方有示例:Chapter 5 Connector/Python Coding
Examples

5.1 Connecting to MySQL Using Connector/Python

5.2 Creating Tables Using Connector/Python

5.3 Inserting Data Using Connector/Python

5.4 Querying Data Using Connector/Python

安装方法:easy_install mysql-connector-python

用法和MySQLdb基本类似,这应该是类似一种协议的东西吧?
查询的时候是支持查询字典的!
connor.connect(*args, **kwargs)
cursor = conn.cursor(dictionary=True)

附加是我自己写的mysql_helper.py
-----------
 1 # -*-
coding: utf8 -*-
 2 # @author: 'zhangzhipeng'
 3 # @date: '2015-04-10'
 4
 5 import logging
 6
 7 import mysql.connector
as connor
 8
 9
10 connor.connect()
11
12
13 class MysqlHelper(object):
14
    """host="localhost",
db="", user="root", passwd="", port=3306, pool_sizer=30,
pool_name="mysql", commit_size=1"""
15
    commit_count
= 0
16
17
    def __init__(self,
*args, **kwargs):
18
        commit_size
= kwargs.get("commit_size", -1)
19
        if commit_size
> -1:
20
            self._commit_size
= commit_size
21
            del kwargs["commit_size"]
22
        else:
23
            self._commit_size
= 1
24
        self._last_row_id
= None
25
        self._conn
= connor.connect(*args, **kwargs)
26
27
    def insert(self,
sql, params=None):
28
        cursor
= self._create_cursor()
29
        try:
30
            cursor.execute(sql,
params)
31
        except Exception,
e:
32
            try:
33
                logging.error("Mysql
Call error. SQL = %s, params = %s,
Error.msg=%s" % (sql,
str(params).encode("utf8"), e))
34
            except:
35
                print sql,
params, e
36
        self._last_row_id
= cursor.lastrowid
37
        self._commit()
38
        return cursor.rowcount
39
40
    def update(self,
sql, params=None):
41
        return self.insert(sql,
params)
42
43
    def delete(self,
sql, params=None):
44
        return self.insert(sql,
params)
45
46
    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: