今天是讀《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()