python连接mysql数据库

 连接mysql数据库,需要安装一个模块,在windows下安装一个程序,我的是2.5版本的python,是这个MySQL-python-1.2.2.win32-py2.5.exe  可以到网上很容易找到。操作数据也是很方便的。下面代码摘自网络。

  1. #-*- encoding: gb2312 -*-
  2. import os, sys, string
  3. import MySQLdb
  4. # 连接数据库 
  5. try:
  6.     conn = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='test1')
  7. except Exception, e:
  8.     print e
  9.     sys.exit()
  10. # 获取cursor对象来进行操作
  11. cursor = conn.cursor()
  12. # 创建表
  13. sql = "create table if not exists test1(name varchar(128) primary key, age int(4))"
  14. cursor.execute(sql)
  15. # 插入数据
  16. sql = "insert into test1(name, age) values ('%s', %d)" % ("zhaowei"23)
  17. try:
  18.     cursor.execute(sql)
  19. except Exception, e:
  20.     print e
  21. sql = "insert into test1(name, age) values ('%s', %d)" % ("张三"21)
  22. try:
  23.     cursor.execute(sql)
  24. except Exception, e:
  25.     print e
  26. # 插入多条
  27. sql = "insert into test1(name, age) values (%s, %s)" 
  28. val = (("李四"24), ("王五"25), ("洪六"26))
  29. try:
  30.     cursor.executemany(sql, val)
  31. except Exception, e:
  32.     print e
  33. #查询出数据
  34. sql = "select * from test1"
  35. cursor.execute(sql)
  36. alldata = cursor.fetchall()
  37. # 如果有数据返回,就循环输出, alldata是有个二维的列表
  38. if alldata:
  39.     for rec in alldata:
  40.         print rec[0], rec[1]
  41. cursor.close()
  42. conn.close()

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值