测试与MySQL服务器的连接

时间:2013-04-21 11:54:53

标签: mysql mysql-python

测试与MySQL服务器的连接的最佳/正确方法是什么。例如,你能ping它吗?我正在使用MySQLdb和python。

我希望我的程序按以下方式构建

....connect to MySQL server 
database = MySQLdb.connect(host="127.0.0.1 etc...

While true:
    **... Check to see if connection is still alive if not reconnect** 

    ... send data to MySQL...
    time.sleep(30)

1 个答案:

答案 0 :(得分:0)

这就是我用过的东西。

import MySQLdb

try:
    import MySQLdb.converters
except ImportError:
    _connarg('conv')

def connect(host='ronak.local', user='my_dev_1', passwd='my_dev_1', db='my_dev1', port=3306):

    try:
        orig_conv = MySQLdb.converters.conversions
        conv_iter = iter(orig_conv)
        convert = dict(zip(conv_iter, [str,] * len(orig_conv.keys())))
        print "Connecting host=%s user=%s db=%s port=%d" % (host, user, db, port)
        conn = MySQLdb.connect(host, user, passwd, db, port, conv=convert)
    except MySQLdb.Error, e:
        print "Error connecting %d: %s" % (e.args[0], e.args[1])
    return conn


def parse_data_and_description(cursor, data, rs_id):

    res = []
    cols = [d[0] for d in cursor.description]

    for i in data:
        res.append(OrderedDict(zip(cols, i)))
    return res
    rs_id=0;

def get_multiple_result_sets():
    conn = connect()
    cursor = conn.cursor( )
    final_list = []
    try:
        conn.autocommit(True)
        cursor.execute ("CALL %s%s" % (sp, args))
        while True:
            rs_id+=1

            data = cursor.fetchall( )
            listout = parse_data_and_description(cursor, data, rs_id)
            print listout
            if cursor.nextset( )==None:
                # This means no more recordsets available
                break
            print "\n"
            # Consolidate all the cursors in a single list
            final_list.append(listout)
        print final_list
    except MySQLdb.Error, e:
        # Lets rollback the transaction in case of an exception
        conn.rollback()
        print "Transaction aborted: %d: %s" % (e.args[0], e.args[1])
        cursor.close( )
        conn.close()
    else:
        # Commit the transaction in case of no failures/exceptions
        conn.commit()
        print "Transaction succeeded"
        cursor.close( )
        conn.close()