# -*- coding: utf-8 -*- mysql
#mysqldb sql
import time, MySQLdb fetch
#鏈接 code
conn=MySQLdb.connect(host="localhost",user="root",passwd="root",db="test",charset="utf8") utf-8
cursor = conn.cursor() 元組的返回值it
conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) 字典的返回值
#刪除表table
sql = "drop table if exists user"class
cursor.execute(sql)test
#建立import
sql = "create table if not exists user(name varchar(128) primary key, created int(10))"
cursor.execute(sql)
#寫入
sql = "insert into user(name,created) values(%s,%s)"
param = ("aaa",int(time.time()))
n = cursor.execute(sql,param)
print 'insert',n
#寫入多行
sql = "insert into user(name,created) values(%s,%s)"
param = (("bbb",int(time.time())), ("ccc",33), ("ddd",44) )
n = cursor.executemany(sql,param)
print 'insertmany',n
#更新
sql = "update user set name=%s where name='aaa'"
param = ("zzz")
n = cursor.execute(sql,param)
print 'update',n
#查詢
n = cursor.execute("select * from user")
for row in cursor.fetchall():
print row
for r in row:
print r
#刪除
sql = "delete from user where name=%s"
param =("bbb")
n = cursor.execute(sql,param)
print 'delete',n
#查詢
n = cursor.execute("select * from user")
print cursor.fetchall()
cursor.close()
#提交
conn.commit()
#關閉
conn.close()