日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Python MySQLdb模塊連接操作mysql數據庫實例

系統 1826 0

mysql是一個優秀的開源數據庫,它現在的應用非常的廣泛,因此很有必要簡單的介紹一下用python操作mysql數據庫的方法。python操作數據庫需要安裝一個第三方的模塊,在http://mysql-python.sourceforge.net/有下載和文檔。

由于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()
# 創建表
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()
# 如果有數據返回,就循環輸出, alldata是有個二維的列表
if alldata:
  for rec in alldata:
    print rec[0], rec[1]


cursor.close()

conn.close()

          


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

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

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦?。?!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 定安县| 寻乌县| 盘锦市| 舒城县| 康乐县| 九江县| 含山县| 漳州市| 泗洪县| 开封县| 黄山市| 明水县| 乌拉特后旗| 民县| 迁安市| 色达县| 和龙市| 肥东县| 亚东县| 醴陵市| 丹凤县| 确山县| 青铜峡市| 龙游县| 奉节县| 临洮县| 沙河市| 安义县| 台南县| 安新县| 横山县| 合作市| 易门县| 北流市| 九寨沟县| 宜州市| 河北省| 察哈| 庆云县| 苏尼特左旗| 印江|