Python+request 使用pymysql链接数据库mysql的操做《十》

     使用指南。pymysql支持python2.7同时也支持python3.x。当前我用的是python2.7。因此过断选择了pymysql的使用,这里注意几点。通常咱们链接数据库为了安全起见,都会要求按照ssl的方式进行链接,可是为了操做和使用的方便,能够跟开发沟统统过添加白名单的方式,链接某个网络,将此网络的IP添加到白名单中,就能够不用ssl的方式链接数据库,直接使用:dbname,host,username,password的方式链接数据库,方便操做。php

 

链接数据库:python

(查询数据)示例代码以下:mysql

#!/usr/bin/env python # -*- coding: utf-8 -*- # Author:lucky,time:2019-06-11

import pymysql,sys import readConfig import json #链接数据库
db = pymysql.connect(host=readConfig.host,user = readConfig.user,passwd=readConfig.passwd,db=readConfig.db) #db:库名 #建立游标 # cur = db.cursor()

#建立游标,结果将已字典的形式返回
cur = db.cursor(pymysql.cursors.DictCursor) # sql = "select bs.uuid,bs.target_type,bs.source,bs.user_uuid,bs.agent_uuid from `behavior_share` bs join user u on u.uuid = bs.user_uuid where u.mobile = '12606666333'" #查询lcj表中存在的数据
sql = "select bs.uuid,bs.agent_uuid from `behavior_share` bs join user u on u.uuid = bs.user_uuid where u.mobile = '12606666333'" cur.execute(sql) #fetchall:获取lcj表中全部的数据
ret1 = cur.fetchall() print(ret1)

打印结果:sql

   

 

 

进阶模式:数据库

      将数据库的配置信息写到ini文件中,经过调用,在py文件中显示,方便配置信息的统一管理,也避免了后期更改数据库的host后,要修改不少地方。json

(1)建立cfg.ini文件。写的内容以下:python3.x

[Test_Env_mysql] ##############此类信息向开发获取#################
host = *********************** user = iber_php passwd = ************* db = iber2_admin

 

(2)建立  readConfig.py 文件,读取ini的配置信息安全

#!/usr/bin/env python # coding=UTF-8

'''此文件主要是获取cfg.ini中对应的配置信息'''
import os import ConfigParser cur_path = os.path.dirname(os.path.realpath(__file__)) configpath = os.path.join(cur_path,"cfg.ini") conf = ConfigParser.ConfigParser() conf.read(configpath) #############获取到mysql的相关信息##################
host = conf.get("Test_Env_mysql","host") user = conf.get("Test_Env_mysql","user") passwd = conf.get("Test_Env_mysql","passwd") db = conf.get("Test_Env_mysql","db")

 

(3)在使用的  attach_mysql.py 文件中直接调用网络

#!/usr/bin/env python # -*- coding: utf-8 -*- # Author:lucky,time:2019-06-11

import pymysql,sys import readConfig import json #链接数据库
db = pymysql.connect(host=readConfig.host,user = readConfig.user,passwd=readConfig.passwd,db=readConfig.db) #db:库名
 ..........剩下的信息更上方的((查询数据)示例代码以下:)写法一致。

 

数据库获取结果的几种常见方式;python2.7

示例一:

sql = "select bs.uuid,bs.agent_uuid from `behavior_share` bs join user u on u.uuid = bs.user_uuid where u.mobile = '12606666333'" cur.execute(sql) #fetchall:获取lcj表中全部的数据
ret1 = cur.fetchall() print(ret1)    #获取全部的查询结果,此处的类型是列表
print len(ret1)     #获取全部结果的条数
print ret1[0]        #获取所得结果为0下标的字典
print type(ret1[0])   #此处的类型是字典
print ret1[0]["uuid"]   #获取所得结果为0下标的字典中的某个值

打印结果:

      

 

实例二:

    获取某行的数据。

sql = "select bs.uuid,bs.agent_uuid from `behavior_share` bs join user u on u.uuid = bs.user_uuid where u.mobile = '12606666333'" cur.execute(sql) print cur.fetchmany(1)   #获取查询结果的前一行的数据
print cur.fetchmany(2)   #获取查询结果的前二行的数据

 

打印结果:

     

相关文章
相关标签/搜索