使用指南。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) #獲取查詢結果的前二行的數據
打印結果: