python3.4连接mysql

来源:互联网 发布:网络出版的类型 编辑:程序博客网 时间:2024/05/22 20:31

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扩展模块缺失,请重新安装

需要连接数据库并读取?

<span style="font-family:Times New Roman;">#connect to mysqlcnx = mysql.connector.connect(user='laowang', password='laowang',        host='127.0.0.1', port=3306, database='laowang')</span>


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

<span style="font-family:Times New Roman;">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</span>


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

<span style="font-family:Times New Roman;">#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()</span>


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

<span style="font-family:Times New Roman;">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]) </span>

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

<span style="font-family:Times New Roman;">test['h'] = base64.b64encode(bytes(url, "utf-8")).decode("utf-8")</span>

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

<span style="font-family:Times New Roman;">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</span>


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

<span style="font-family:Times New Roman;">#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</span>









0 0
原创粉丝点击