mysql是一個(gè)優(yōu)秀的開(kāi)源數(shù)據(jù)庫(kù),它現(xiàn)在的應(yīng)用非常的廣泛,因此很有必要簡(jiǎn)單的介紹一下用python操作mysql數(shù)據(jù)庫(kù)的方法。python操作數(shù)據(jù)庫(kù)需要安裝一個(gè)第三方的模塊,在http://mysql-python.sourceforge.net/有下載和文檔。
由于python的數(shù)據(jù)庫(kù)模塊有專(zhuān)門(mén)的數(shù)據(jù)庫(kù)模塊的規(guī)范,所以,其實(shí)不管使用哪種數(shù)據(jù)庫(kù)的方法都大同小異的,這里就給出一段示范的代碼:
#-*- encoding: gb2312 -*- import os, sys, string import MySQLdb # 連接數(shù)據(jù)庫(kù) try: conn = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='test1') except Exception, e: print e sys.exit() # 獲取cursor對(duì)象來(lái)進(jìn)行操作 cursor = conn.cursor() # 創(chuàng)建表 sql = "create table if not exists test1(name varchar(128) primary key, age int(4))" cursor.execute(sql) # 插入數(shù)據(jù) sql = "insert into test1(name, age) values ('%s', %d)" % ("zhaowei", 23) try: cursor.execute(sql) except Exception, e: print e sql = "insert into test1(name, age) values ('%s', %d)" % ("張三", 21) try: cursor.execute(sql) except Exception, e: print e # 插入多條 sql = "insert into test1(name, age) values (%s, %s)" val = (("李四", 24), ("王五", 25), ("洪六", 26)) try: cursor.executemany(sql, val) except Exception, e: print e #查詢(xún)出數(shù)據(jù) sql = "select * from test1" cursor.execute(sql) alldata = cursor.fetchall() # 如果有數(shù)據(jù)返回,就循環(huán)輸出, alldata是有個(gè)二維的列表 if alldata: for rec in alldata: print rec[0], rec[1] cursor.close() conn.close()
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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