码迷,mamicode.com
首页 > 数据库 > 详细

python下的MySQLdb使用

时间:2015-06-05 12:31:33      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

# -*- coding: utf-8 -*-     

#mysqldb    

import time, MySQLdb    

   

#连接    

conn=MySQLdb.connect(host="localhost",user="root",passwd="root",db="test",charset="utf8")  

cursor = conn.cursor()    元组的返回值

conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) 字典的返回值


#删除表

sql = "drop table if exists user"

cursor.execute(sql)


#创建

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()   


python下的MySQLdb使用

标签:

原文地址:http://my.oschina.net/u/232595/blog/425176

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!