Python MySQLdb模塊例子

#-*- 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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章