python连接MySQL数据库脚本

python连接数据库脚本

代码如下(示例):

# -*- coding: UTF-8 -*-
import MySQLdb
import traceback
import time, logging, json, datetime, csv, cStringIO, codecs, decimal, re
from DBUtils.PooledDB import PooledDB
g_dbIp = '127.0.0.1'
g_user = 'root'
g_password = '123456'
g_dbName = 'XXX'


class CJsonEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, decimal.Decimal):
            return int(obj)
        else:
            return json.JSONEncoder.default(self, obj)


g__pool = PooledDB(creator=MySQLdb, mincached=3, maxcached=20, host=g_dbIp, user=g_user, passwd=g_password, maxconnections=20, blocking=True, db=g_dbName, use_unicode=True, charset='utf8')

class MysqlDbo(object):
    def write(self, sql):
        conn = g__pool.connection()
        cursor = conn.cursor()
        try:
            cursor.execute(sql)
            conn.commit()
        except:
            conn.rollback()

        cursor.close()
        conn.close()


    def read(self, sql):
        conn = g__pool.connection()
        cursor = conn.cursor()
        data = '[]'
        try:
            rs = cursor.execute(sql)
            rows = cursor.fetchall()
            data = json.dumps(rows, cls=CJsonEncoder)
        except:
            print("read fail")

        cursor.close()
        conn.close()
        return data


if __name__ == '__main__':
    dbo = MysqlDbo()
    a = dbo.read('select protocol,count(*) as count from traffics where protocol in ("ARP","ICMP", "SYN", "PAYLOAD") group by protocol having count>0')

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值