Mysql是一个优秀的开源数据库,它现在的应用非常的广泛,因此很有必要简单的介绍一下用python操作mysql数据库的方法。Python操作数据库需要安装一个第三方的模块。
在成都网站建设、成都网站制作中从网站色彩、结构布局、栏目设置、关键词群组等细微处着手,突出企业的产品/服务/品牌,帮助企业锁定精准用户,提高在线咨询和转化,使成都网站营销成为有效果、有回报的无锡营销推广。创新互联专业成都网站建设十多年了,客户满意度97.8%,欢迎成都创新互联客户联系。
由于Python的数据库模块有专门的数据库模块的规范,所以,其实不管使用哪种数据库的方法都大同小异的,这里就给出一段示范的Python操作代码:
- #-*- encoding: gb2312 -*-
- import os, sys, string
- import 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) primary 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 e
- sql = "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()
【编辑推荐】
分享题目:对Python操作方法说明
地址分享:http://www.csdahua.cn/qtweb/news28/481178.html
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网