本文實例講述了Python操作MySQL簡單實現方法。分享給大家供大家參考。具體分析如下:
一、安裝:
安裝MySQL
安裝MySQL不用多說了,下載下來安裝就是,沒有特別需要注意的地方。
一個下載地址:點擊打開鏈接
二、示例:
import MySQLdb
?
#查詢數量
def Count(cur):
?? count=cur.execute('select * from Student')
?? print 'there has %s rows record' % count
???
#插入
def Insert(cur):
?? sql = "insert into Student(ID,Name,Age,Sex)values(%s,%s,%s,%s)"
?? param = (2,'xiaoming',24,'boy')
?? cur.execute(sql,param)
?
#查詢
def? Select(cur):?
?? n = cur.execute("select * from Student")???
?? print "------"
?? for row in cur.fetchall():???
????? for r in row:???
???????? print r
????? print "------"??
#更新
def Update(cur):
?? sql = "update Student set Name = %s where ID = 2"?
?? param = ("xiaoxue")???
?? count = cur.execute(sql,param)
?
#刪除
def Delete(cur):???
?? sql = "delete from Student where Name = %s"?
?? param =("xiaoxue")???
?? n = cur.execute(sql,param)??
?
try:
?? conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',db='python',port=3306)
?? cur=conn.cursor()
?? #數量
?? Count(cur)
?? #查詢
?? Select(cur)
?? #插入
?? Insert(cur)
?? print "插入之后"
?? #查詢
?? Select(cur)
?? #更新
?? Update(cur)
?? print "更新之后"
?? #查詢
?? Select(cur)
?? #刪除
?? Delete(cur)
?? print "刪除之后"
?? #查詢
?? Select(cur)
???
?? cur.close()
?? conn.close()
???
except MySQLdb.Error,e:
?? print "Mysql Error %d: %s" % (e.args[0], e.args[1])
希望本文所述對大家的Python程序設計有所幫助。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
