python 數(shù)據(jù)分析基礎(chǔ) day12-python調(diào)用mysql

今天是讀《python數(shù)據(jù)分析基礎(chǔ)》的第11天,今天的讀書筆記的內(nèi)容為通過MysqlcCient模塊來使用mysql數(shù)據(jù)庫。

mysqlcilent介紹

mysql與python連接的包名為mysql-python, 不過在python3.x中這個(gè)包的名字為mysqlclient,調(diào)用時(shí)包的名稱則為MySQLdb。
使用方式與sqlite3類似,先鏈接數(shù)據(jù)庫,再創(chuàng)建游標(biāo),通過cursor.execute()執(zhí)行sql語句,再通過connection.commit()提交事務(wù)。
注:
1.進(jìn)行以下操作時(shí),必須確保mysql服務(wù)已經(jīng)開啟。
2.下文操作所涉及的數(shù)據(jù)庫pydatabase已實(shí)現(xiàn)通過mysql生成。

創(chuàng)建數(shù)據(jù)表

import MySQLdb

#連接mysql數(shù)據(jù)庫
con=MySQLdb.connect(host='localhost',port=3306,db='pydatabase',user='user',passwd='pass')
#生成游標(biāo)
cur=con.cursor()

#創(chuàng)建表
cur.execute('CREATE TABLE IF NOT EXISTS test(ID long,text varchar(20),score float)')

#關(guān)閉游標(biāo)及數(shù)據(jù)庫連接
cur.close()
con.close()

插入數(shù)據(jù)

import MySQLdb

#連接mysql數(shù)據(jù)庫
con=MySQLdb.connect(host='localhost',port=3306,db='pydatabase',user='user',passwd='pass')
#生成游標(biāo)
cur=con.cursor()

#插入數(shù)據(jù)
data=[(1,'a',12.5),(2,'b',10.3),(3,'c',11.0)]
for row in data:
    cur.execute('INSERT INTO test VALUES(%s,%s,%s);',row)
con.commit()

#關(guān)閉游標(biāo)及數(shù)據(jù)庫連接
cur.close()
con.close()

選取數(shù)據(jù)

import MySQLdb

#連接mysql數(shù)據(jù)庫
con=MySQLdb.connect(host='localhost',port=3306,db='pydatabase',user='user',passwd='pass')
#生成游標(biāo)
cur=con.cursor()

#選取數(shù)據(jù)
cur.execute('SELECT * FROM test;')
rows=cur.fetchall()
for row in rows:
    print(row)

#關(guān)閉游標(biāo)及數(shù)據(jù)庫連接
cur.close()
con.close()

修改數(shù)據(jù)

import MySQLdb

#連接mysql數(shù)據(jù)庫
con=MySQLdb.connect(host='localhost',port=3306,db='pydatabase',user='user',passwd='pass')
#生成游標(biāo)
cur=con.cursor()

#更新數(shù)據(jù)
cur.execute('UPDATE test SET score=score+1.0;')
con.commit()

#關(guān)閉游標(biāo)及數(shù)據(jù)庫連接
cur.close()
con.close()

刪除數(shù)據(jù)

import MySQLdb

#連接mysql數(shù)據(jù)庫
con=MySQLdb.connect(host='localhost',port=3306,db='pydatabase',user='user',passwd='pass')
#生成游標(biāo)
cur=con.cursor()

#刪除數(shù)據(jù)
cur.execute('DELETE FROM test;')

#關(guān)閉游標(biāo)及數(shù)據(jù)庫連接
cur.close()
con.close()

刪除表

import MySQLdb

#連接mysql數(shù)據(jù)庫
con=MySQLdb.connect(host='localhost',port=3306,db='pydatabase',user='user',passwd='pass')
#生成游標(biāo)
cur=con.cursor()

#刪除表
cur.execute('DROP TABLE test;')

#關(guān)閉游標(biāo)及數(shù)據(jù)庫連接
cur.close()
con.close()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容