python mysqldb 清除缓存_python MySQLdb的操作

1.import MySQLdb;

2.与mysql数据库建立连接:con=MySQLdb.connect(user='root',db='mysql',passwd='dingjia',host='localhost')

3.当没有游标cursor对象时候,连接对象可以使用query()方法,执行sql查询

con.query('create database test')

4.使用游标对象和execute()方法来执行sql

cur=con.cursor()  返回游标对象

cur.execute('create table users(login varchar(8),uid INT)')

cur.execute('insert into users values('hzhida',1000)')

cur.execute('select *from users')

for data in cur.fetchall(): 输出查询结果得到的数据

print '%s\t%s' % data

cur.close()  关闭游标

con.commit()  提交事务

con.close()     关闭连接

python cookbook 的例子:

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

importMySQLdb,cPickle#连接到数据库,并获得图标

connection = MySQLdb.connect(user = 'root',db='zm',passwd = '36039975',host='localhost')

cursor=connection.cursor()#创建一个新表以用于试验

cursor.execute('create table test(name TEXT, ablob BLOB)')try:#准备一些BLOB用于测试

names = 'aramis', 'athos','porthos'data={ }for name innames:

datum=list(name)

datum.sort()

data[name]= cPickle.dumps(datum,2)#execute insert

sql = "insert into test values(%s, %s)"

for name innames:

cursor.execute(sql,(name,MySQLdb.escape_string(data[name])))#check in the database

sql = "select name, ablob from test order by name"cursor.execute(sql)for name , blob incursor.fetchall():printname, cPickle.loads(blob), cPickle.loads(data[name])finally:#finish,delete table and close connection

cursor.execute("drop table test")

cursor.close()

connection.close()

输出:

aramis ['a', 'a', 'i', 'm', 'r', 's'] ['a', 'a', 'i', 'm', 'r', 's']

athos ['a', 'h', 'o', 's', 't'] ['a', 'h', 'o', 's', 't']

porthos ['h', 'o', 'o', 'p', 'r', 's', 't'] ['h', 'o', 'o', 'p', 'r', 's', 't']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值