• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python MySQLdb模块连接操作mysql数据库实例

python 搞代码 4年前 (2022-01-09) 23次浏览 已收录 0个评论

mysql是一个优秀的开源数据库,它现在的应用非常的广泛,因此很有必要简单的介绍一下用python操作mysql数据库的方法。python操作数据库需要安装一个第三方的模块,在http://mysql-python.sourceforge.net/有下载和文档。

由于python的数据库模块有专门的数据库模块的规范,所以,其实不管使用哪种数据库的方法都大同小异的,这里就给出一段示范的代码:

#-*- encoding: gb2312 -*-import os, sys, stringimport MySQLdb# 连接数据库 try:  conn = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='test1')except Exception, e:  print e  sys.exit()# 获取cursor对象来进行操作cursor = conn.cursor()# 创建表sql = "create table if not exists test1(name varchar(128) prim<i style="color:transparent">本文来源gaodai$ma#com搞$$代**码)网8</i>ary key, age int(4))"cursor.execute(sql)# 插入数据sql = "insert into test1(name, age) values ('%s', %d)" % ("zhaowei", 23)try:  cursor.execute(sql)except Exception, e:  print esql = "insert into test1(name, age) values ('%s', %d)" % ("张三", 21)try:  cursor.execute(sql)except Exception, e:  print e# 插入多条sql = "insert into test1(name, age) values (%s, %s)" val = (("李四", 24), ("王五", 25), ("洪六", 26))try:  cursor.executemany(sql, val)except Exception, e:  print e#查询出数据sql = "select * from test1"cursor.execute(sql)alldata = cursor.fetchall()# 如果有数据返回,就循环输出, alldata是有个二维的列表if alldata:  for rec in alldata:    print rec[0], rec[1]cursor.close()conn.close()

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python MySQLdb模块连接操作mysql数据库实例
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址