Python数据库数据采集

打开一个mysql连接,从选定的数据库表中选择所有内容,将数据放入数组,返回数组并递归写出

下面是php相关实现,请各位翻译成python:

img

img

自己拿这段代码改一下嘛,没看到啥递归操作呀。 就是建表,提示,插入随机字符串。

 
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)