windows环境下,连接mysql数据库,从表中导出内容,将结果用数组形式写出

连接到 mysql 数据库,从表中选择所有内容,将结果放入数组,然后将数组写出来。


import pymysql

#连接MySQL
def Connect():    
    try:
        db = pymysql.connect(host = "10.202.x.x", user = "user1", password = "xxxxxx", db = "default", charset = 'utf8')
        return db
    except:
        return ""


def row_copy_list(rows):
    ret_list = []
    for row in rows:
        ret_r = []
        for r in row:
            if r is None:
                ret_r.append("")
            else:
                ret_r.append(r)
        ret_list.append(ret_r)
    return ret_list

# str_sql 就是你查询语句
def get_query(str_sql):
    db = Connect()
    if db == "":
        print( "数据库连接错误")
        return ""
    else:
        try:
            cursor = db.cursor()
            cursor.execute(str_sql)
            row = row_copy_list(cursor.fetchall())
            cursor.close()
            db.close()
            return row
        except Exception as e:
            print("数据库查询出错\n" + repr(e))
    return ""


data_list = get_query("select name,age from db1.students")
for di in data_list:
    print(di)