博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python3.4连接mysql
阅读量:3520 次
发布时间:2019-05-20

本文共 2183 字,大约阅读时间需要 7 分钟。

python3.X并没有附带Mysql扩展,需要自行安装,步骤如下:

在(http://dev.mysql.com/downloads/connector/python/)下载mysql扩展安装包,注意选择“platform Indenpent”,这样才是.tar.gz格式的源代码,解压即可。

进入mysql-connector-python-2.0.4目录,执行$python  ./setup.py install,自动完成安装

注意事项:

$python 为python所在路径,注意选择一个完整的python3.x,如果提示python扩展模块缺失,请重新安装

需要连接数据库并读取?

#connect to mysqlcnx = mysql.connector.connect(user='laowang', password='laowang',        host='127.0.0.1', port=3306, database='laowang')

当查询结果返回一行,需要获取每一列:

def getDistTaskInfo(cnx, distId):    cursor = cnx.cursor()    stmt_query = "SELECT * FROM dist WHERE id = '%d'" % testId    cursor.execute(stmt_query)    data = cursor.fetchone()    cnt = 0;    for row in data:        g_distAr[g_distAttr[cnt]] = row        cnt = cnt + 1

当查询结果返回多个数据行:

#get info from dist_group table, then we can get host from each groupdef getAllGroupId(cnx, testId):    groupDict = {}    cursor = cnx.cursor()    stmt_query = "SELECT * FROM laowang_test WHERE dist_id = '%d'" % testId    cursor.execute(stmt_query)    data = cursor.fetchone()    while data is not None:        cnt = 0        for row in data:            groupDict[g_distGroupAttr[cnt]] = row            cnt = cnt + 1        g_distGroup.append(groupDict)        data = cursor.fetchone()

python从数据库中读出的内容,并不是一个AR模型,因此需要自行保存数据表结构:

def getTableStructure(cnx, table, g_dict):    cursor = cnx.cursor()    stmt_query = "desc %s" % table    cursor.execute(stmt_query)    info = cursor.fetchall()    for row in info:        g_dict.append(row[0]) 

需要模仿php的base64_encode()功能?python同样可以提供:

test['h'] = base64.b64encode(bytes(url, "utf-8")).decode("utf-8")

需要执行一段shell命令,并查看返回值?如下可以做到:

def exec_and_return_stdout(cmd):    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)    global g_exec_ret    g_exec_ret = p.wait()    stdout = bytes.decode(p.stdout.read())    return stdout

需要访问一个url,并解析json?

#get machine from nodedef getNodeHosts(node):    host = []    url = url + node    ret = urllib.request.urlopen(url)    res = ret.read().decode('utf-8')    json_ret = json.loads(res)    data = json_ret['data']    if(0 == len(machine)):        return host    for ele in machine:        host.append(ele['name'])    return host

转载地址:http://lzoqj.baihongyu.com/

你可能感兴趣的文章
js对象的深拷贝,你真的觉得很简单吗?
查看>>
你真的了解map方法吗?手动实现数组map方法。
查看>>
带你手动实现call方法,让你收获满满
查看>>
前端知识体系
查看>>
查找入职员工时间排名倒数第三的员工所有信息
查看>>
使用join查询方式找出没有分类的电影id以及名称
查看>>
Qt教程(2) : Qt元对象系统
查看>>
驱动开发误用指针错误:Unable to handle kernel NULL pointer dereference at virtual address
查看>>
Linux部署DocSystem知识/文件管理系统
查看>>
Centos7开机自启动脚本无法使用备用方案
查看>>
jvm虚拟机内存详解
查看>>
线程的创建方式
查看>>
DNS是什么
查看>>
mapreduce自定义分组、自定义分区、二次排序
查看>>
Hbase架构
查看>>
spark运行模式
查看>>
PaddleX的C++使用
查看>>
MyBatis-Plus代码生成器
查看>>
我的第一个SpringBoot项目(一)
查看>>
回文数
查看>>