新聞中心
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è)第三方的模塊。

在成都網(wǎng)站建設(shè)、成都網(wǎng)站制作中從網(wǎng)站色彩、結(jié)構(gòu)布局、欄目設(shè)置、關(guān)鍵詞群組等細(xì)微處著手,突出企業(yè)的產(chǎn)品/服務(wù)/品牌,幫助企業(yè)鎖定精準(zhǔn)用戶,提高在線咨詢和轉(zhuǎn)化,使成都網(wǎng)站營(yíng)銷成為有效果、有回報(bào)的無(wú)錫營(yíng)銷推廣。創(chuàng)新互聯(lián)專業(yè)成都網(wǎng)站建設(shè)十多年了,客戶滿意度97.8%,歡迎成都創(chuàng)新互聯(lián)客戶聯(lián)系。
由于Python的數(shù)據(jù)庫(kù)模塊有專門(mén)的數(shù)據(jù)庫(kù)模塊的規(guī)范,所以,其實(shí)不管使用哪種數(shù)據(jù)庫(kù)的方法都大同小異的,這里就給出一段示范的Python操作代碼:
- #-*- 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
- #查詢出數(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()
【編輯推薦】
- 如何使Python嵌入C++應(yīng)用程序?
- 深入探討Ruby與Python語(yǔ)法比較
- Python學(xué)習(xí)資料介紹分享
- Python學(xué)習(xí)經(jīng)驗(yàn)談:版本、IDE選擇及編碼解決方案
- 淺析Python的GIL和線程安全
名稱欄目:對(duì)Python操作方法說(shuō)明
鏈接分享:http://fisionsoft.com.cn/article/coppioj.html


咨詢
建站咨詢
