Chinaunix首页 | 论坛 | 博客
  • 博客访问: 123664
  • 博文数量: 83
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 585
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-13 10:26
个人简介

- 毅力与勇气是事业的双飞翼; - 在尝试中成长,在失败中奋起。 - 概览 -> 细读 -> 概览 - 书不在多,在于精。

文章分类

全部博文(83)

文章存档

2016年(2)

2015年(6)

2014年(75)

我的朋友

分类: Python/Ruby

2015-09-18 20:25:46

http://www.cnblogs.com/hzhida/archive/2012/08/02/2619848.html

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-*- import MySQLdb,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 in names:
        datum = list(name)
        datum.sort()
        data[name] = cPickle.dumps(datum,2) #execute insert sql = "insert into test values(%s, %s)" for name in names:
        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 in cursor.fetchall(): print name, 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']

复制代码
Live together,or Die alone!
阅读(490) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~