Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1367008
  • 博文数量: 243
  • 博客积分: 888
  • 博客等级: 准尉
  • 技术积分: 2955
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-05 14:33
个人简介

漫漫长路,其修远兮!

文章分类

全部博文(243)

文章存档

2017年(2)

2016年(22)

2015年(32)

2014年(57)

2013年(107)

2012年(23)

分类: Python/Ruby

2014-03-27 11:26:02


点击(此处)折叠或打开

  1. #!/usr/bin/python2.7
  2. # coding=utf-8

  3. import MySQLdb
  4. import sys

  5. host = '127.0.0.1'
  6. user = 'xxx'
  7. pwd = 'xxxx' # to be modified.
  8. port = '3306'
  9. db = 'test'


  10. if __name__ == '__main__':
  11.     conn = MySQLdb.connect(host=host, user=user, passwd=pwd, db=db, port=3306, charset='utf8');
  12.     try:
  13.         conn.ping()
  14.     except:
  15.         print 'failed to connect MySQL.'
  16.     sql = 'select * from stat_app_open where id = 4128'
  17.     cur = conn.cursor()
  18.     cur.execute(sql)
  19.     row = cur.fetchone()
  20.     for i in row:
  21.         print i
  22.     cur.close()
  23.     conn.close()
  24.     sys.exit()

点击(此处)折叠或打开

  1. # -*- coding: utf-8 -*-
  2. #mysqldb
  3. import time, MySQLdb
  4.    
  5. #连接
  6. conn=MySQLdb.connect(host="localhost",user="root",passwd="root",db="test",charset="utf8")
  7. cursor = conn.cursor()

  8. #删除表
  9. sql = "drop table if exists user"
  10. cursor.execute(sql)

  11. #创建
  12. sql = "create table if not exists user(name varchar(128) primary key, created int(10))"
  13. cursor.execute(sql)

  14. #写入
  15. sql = "insert into user(name,created) values(%s,%s)"
  16. param = ("aaa",int(time.time()))
  17. n = cursor.execute(sql,param)
  18. print 'insert',n
  19.    
  20. #写入多行
  21. sql = "insert into user(name,created) values(%s,%s)"
  22. param = (("bbb",int(time.time())), ("ccc",33), ("ddd",44) )
  23. n = cursor.executemany(sql,param)
  24. print 'insertmany',n

  25. #更新
  26. sql = "update user set name=%s where name='aaa'"
  27. param = ("zzz")
  28. n = cursor.execute(sql,param)
  29. print 'update',n
  30.    
  31. #查询
  32. n = cursor.execute("select * from user")
  33. for row in cursor.fetchall():
  34.     print row
  35.     for r in row:
  36.         print r
  37.    
  38. #删除
  39. sql = "delete from user where name=%s"
  40. param =("bbb")
  41. n = cursor.execute(sql,param)
  42. print 'delete',n

  43. #查询
  44. n = cursor.execute("select * from user")
  45. print cursor.fetchall()

  46. cursor.close()
  47.    
  48. #提交
  49. conn.commit()
  50. #关闭
  51. conn.close()

安装步骤
1.python setup.py build
报错error: command 'gcc' failed with exit status 1
sudo apt-get install python-dev
2.python setup.py install

安装测试
>>>import MySQLdb

使用
a.创建连接
conn=MySQLdb.connect(host=host,user=user,passwd=pwd,db=name,port=3306,charset='utf8')
b.生成游标
cur=conn.cursor()
c.操作游标
执行sql语句
n=cur.execute(sql)
查询数据
n=cur.execute(sql)
for row in cur.fetchone()
   print row
for row in cur.fetchall()
   print row
   for i in row
      print i
for row in cur.fetchall()
   print row[i]

阅读(1047) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~