本文共 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/