python下的MySQLdb使用

1. python2 使用MySQLdb

# coding:utf-8
import sys
import MySQLdb
from functools import reduce
import datetime

config = {
        'host': '**.100.**.1**',
        'port': 3306,
        'user': 'root',
        'passwd': '123456',
        'db': 'bot',
        'charset': 'utf8'
    }

    conn = MySQLdb.connect(**config)

    cursor = conn.cursor()
    cursor.execute('select uuid from tb where state = 0')
    result_values = cursor.fetchall()
    try:

        for line in result_values:
            uuid = line[0]
            # 查詢機器人反饋的話術
            sql_robot_words = "select b.robot_words,b.corpus_score from tb_mm_record a LEFT JOIN mm_voice b " \
                              "on a.voice_id = b.id where uuid = '%s'" % uuid
            cursor.execute(sql_robot_words)
            values_robot_words = cursor.fetchall()

            b = list(word[1] for word in values_robot_words if word[0] != None)

            if len(b):
                customer_score = reduce(lambda x, y: x + y, b)
            else:
                customer_score = len(b)
            state = 1
            sql_update = "UPDATE mm_cdr SET customer_score = '%d',state = '%s'" % (customer_score, state) + "WHERE uuid = '%s'" % uuid
            cursor.execute(sql_update)
            conn.commit()
    except:
        # Rollback in case there is any error
        conn.rollback()
    # 關閉數(shù)據(jù)庫連接
    cursor.close()
    conn.close()

2. python2 使用 mySQL

python 更新插入mySQL數(shù)據(jù)庫

3. python3 使用pymysql

3.1 首先測試數(shù)據(jù)庫的連接test.py

# coding:utf-8
import pymysql

def connectdb():
    print('連接到mysql服務器...')
    db = pymysql.connect(
        host="localhost",
        user="op",
        passwd="123456",
        port=3306,
        db="voic",
        charset='utf8',
        cursorclass=pymysql.cursors.DictCursor)
    print('連接上了!')
    return db

if __name__ == '__main__':
    connectdb()

輸出:

連接到mysql服務器...
連接上了!

3.2 配置數(shù)據(jù)庫信息

配置文件mysql_configurate

{"passwd": "123456", "charset": "utf8mb4", "port": 3306, "host": "27.140.215.133", "user": "op", "db": "voic"}

py 文件 mysql_configurate.py

# coding:utf-8
from functools import reduce
import datetime
import pymysql
from threading import Timer



def callValueScore():
    print('開始吧')

    f_read = open('.\mysql_configurate', 'r')
    data = f_read.readline()
    print(data, type(data))
    d = eval(data)
    config = {
        'host': d['host'],
        'port': d['port'],
        'user': d['user'],
        'passwd': d['passwd'],
        'db': d['db'],
        'charset': d['charset']
    }

    conn = pymysql.connect(**config)

    cursor = conn.cursor()
    cursor.execute('select uuid from tb_cdr where state = 1')
    result_values = cursor.fetchall()
    print(len(result_values))

    try:

        for line in result_values:
            break
            uuid = line[0]
            # 查詢機器人反饋的話術
            sql_robot_words = "select b.robot_words,b.corpus_score from tb_reply_record a LEFT JOIN tb_voice b " \
                              "on a.voice_id = b.id where uuid = '%s'" % uuid
            cursor.execute(sql_robot_words)
            values_robot_words = cursor.fetchall()

            b = list(word[1] for word in values_robot_words if word[0] != None)

            if len(b):
                customer_score = reduce(lambda x, y: x + y, b)
            else:
                customer_score = len(b)

            print(customer_score)
            state = 1
            # sql_update = "UPDATE tb_cdr SET customer_score = '%d',state = '%s'" % (customer_score, state) + "WHERE uuid = '%s'" % uuid
            # cursor.execute(sql_update)

            conn.commit()
    except:
        # Rollback in case there is any error
        conn.rollback()
    # 關閉數(shù)據(jù)庫連接
    cursor.close()
    conn.close()

3.3 寫入數(shù)據(jù)庫信息

# coding:utf-8
import json

def testConfigurate():
    data = {
        'host': '27.110.215.127',
        'port': 3306,
        'user': 'ops',
        'passwd': '123456',
        'db': 'voic',
        'charset': 'utf8mb4'
    }
    f = open('.\mysql_configurate', 'w')
    data_str = json.dumps(data)
    print(data_str)
    print(type(data_str))
    d = json.loads(data_str)
    print(d['db'],type(d['db']))
    print(d['port'], type(d['port']))
    f.write(data_str)

參考鏈接:
python 更新插入mySQL數(shù)據(jù)庫
安裝
Python連接MySQL數(shù)據(jù)庫
python下的MySQLdb使用

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末户辫,一起剝皮案震驚了整個濱河市畜普,隨后出現(xiàn)的幾起案子旬渠,更是在濱河造成了極大的恐慌,老刑警劉巖蔗彤,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異列吼,居然都是意外死亡乎芳,警方通過查閱死者的電腦和手機遵蚜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門帖池,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人吭净,你說我怎么就攤上這事睡汹。” “怎么了攒钳?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵帮孔,是天一觀的道長。 經(jīng)常有香客問我不撑,道長文兢,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任焕檬,我火速辦了婚禮姆坚,結果婚禮上,老公的妹妹穿的比我還像新娘实愚。我一直安慰自己兼呵,他們只是感情好,可當我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布腊敲。 她就那樣靜靜地躺著击喂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪碰辅。 梳的紋絲不亂的頭發(fā)上懂昂,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天,我揣著相機與錄音没宾,去河邊找鬼凌彬。 笑死,一個胖子當著我的面吹牛循衰,可吹牛的內容都是我干的铲敛。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼会钝,長吁一口氣:“原來是場噩夢啊……” “哼伐蒋!你這毒婦竟也來了?” 一聲冷哼從身側響起顽素,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤咽弦,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后胁出,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡段审,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年全蝶,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡抑淫,死狀恐怖绷落,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情始苇,我是刑警寧澤砌烁,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站催式,受9級特大地震影響函喉,放射性物質發(fā)生泄漏。R本人自食惡果不足惜荣月,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一管呵、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧哺窄,春花似錦捐下、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至生年,卻和暖如春婴程,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背晶框。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工排抬, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人授段。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓蹲蒲,卻偏偏與公主長得像,于是被迫代替她去往敵國和親侵贵。 傳聞我的和親對象是個殘疾皇子届搁,可洞房花燭夜當晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內容