新聞中心
這里有您想知道的互聯網營銷解決方案
對Python操作方法說明
Mysql是一個優(yōu)秀的開源數據庫,它現在的應用非常的廣泛,因此很有必要簡單的介紹一下用python操作mysql數據庫的方法。Python操作數據庫需要安裝一個第三方的模塊。

在成都網站建設、成都網站制作中從網站色彩、結構布局、欄目設置、關鍵詞群組等細微處著手,突出企業(yè)的產品/服務/品牌,幫助企業(yè)鎖定精準用戶,提高在線咨詢和轉化,使成都網站營銷成為有效果、有回報的無錫營銷推廣。創(chuàng)新互聯專業(yè)成都網站建設十多年了,客戶滿意度97.8%,歡迎成都創(chuàng)新互聯客戶聯系。
由于Python的數據庫模塊有專門的數據庫模塊的規(guī)范,所以,其實不管使用哪種數據庫的方法都大同小異的,這里就給出一段示范的Python操作代碼:
- #-*- encoding: gb2312 -*-
- import os, sys, string
- import MySQLdb
- # 連接數據庫
- try:
- conn = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='test1')
- except Exception, e:
- print e
- sys.exit()
- # 獲取cursor對象來進行操作
- cursor = conn.cursor()
- # 創(chuàng)建表
- sql = "create table if not exists test1(name varchar(128) primary key, age int(4))"
- cursor.execute(sql)
- # 插入數據
- 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
- #查詢出數據
- sql = "select * from test1"
- cursor.execute(sql)
- alldata = cursor.fetchall()
- # 如果有數據返回,就循環(huán)輸出, alldata是有個二維的列表
- if alldata:
- for rec in alldata:
- print rec[0], rec[1]
- cursor.close()
- conn.close()
【編輯推薦】
- 如何使Python嵌入C++應用程序?
- 深入探討Ruby與Python語法比較
- Python學習資料介紹分享
- Python學習經驗談:版本、IDE選擇及編碼解決方案
- 淺析Python的GIL和線程安全
網頁名稱:對Python操作方法說明
鏈接URL:http://www.dlmjj.cn/article/coppioj.html


咨詢
建站咨詢
