Python中操作MySQL入門實(shí)例
一、安裝MySQL-python
# yum install -y MySQL-python
二、打開數(shù)據(jù)庫連接
#!/usr/bin/python
import MySQLdb
conn = MySQLdb.connect(user='root',passwd='admin',host='127.0.0.1')
conn.select_db('test')
cur = conn.cursor()
三、操作數(shù)據(jù)庫
def insertdb():
sql = 'insert into test(name,`sort`) values ("%s","%s")'
exsql = sql % ('hello','python')
cur.execute(exsql)
conn.commit()
return 'insert success'
def selectdb():
sql = 'select `name` from test where `sort` = "%s"'
exsql = sql % ('python')
count = cur.execute(exsql)
for row in cur:
print row
print 'cursor move to top:'
cur.scroll(0,'absolute')
row = cur.fetchone()
while row is not None:
print row
row = cur.fetchone()
print 'cursor move to top:'
cur.scroll(0,'absolute')
many = cur.fetchmany(count)
print many
def deletedb():
sql = 'delete from test where `sort` = "%s"'
exsql = sql % ('python')
cur.execute(exsql)
conn.commit()
return 'delete success'
print insertdb()
print insertdb()
selectdb()
print deletedb()
四、關(guān)閉連接
cur.close()
conn.close()
注意順序。
相關(guān)文章
Python操作Excel把數(shù)據(jù)分給sheet
這篇文章主要介紹了Python操作Excel把數(shù)據(jù)分給sheet,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05
python中實(shí)現(xiàn)延時(shí)回調(diào)普通函數(shù)示例代碼
這篇文章主要給大家介紹了關(guān)于python中實(shí)現(xiàn)延時(shí)回調(diào)普通函數(shù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09
Python3轉(zhuǎn)換html到pdf的不同解決方案
今天小編就為大家分享一篇關(guān)于Python3轉(zhuǎn)換html到pdf的不同解決方案,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-03-03
python 實(shí)現(xiàn)批量替換文本中的某部分內(nèi)容
今天小編就為大家分享一篇python 實(shí)現(xiàn)批量替換文本中的某部分內(nèi)容,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Python matplotlib繪圖設(shè)置圖例案例
這篇文章主要給大家分享Python matplotlib繪圖設(shè)置圖例案例,過程會(huì)學(xué)到edgecolor 圖例邊框線顏色 facecolor 圖例背景色 shadow 是否添加陰影 title 圖例標(biāo)題 fontsize 設(shè)置字體大小,小編覺得挺有意思的,感興趣的小伙伴也可以參考一下2021-12-12

