Python MySQLdb模块,pythonmysqldb模块,mysql是一个优秀的开
Python MySQLdb模块,pythonmysqldb模块,mysql是一个优秀的开
mysql是一个优秀的开源数据库,它现在的应用非常的广泛,因此很有必要简单的介绍一下用python操作mysql数据库的方法。python操作数据库需要安装一个第三方的模块,在http://mysql-python.sourceforge.net/有下载和文档。
#-*- 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) 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 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()#该片段来自于http://byrx.net
相关内容
- Randomized Select,randomizedselect,import rando
- 抽取新闻,,经常看财经新闻,写了个简
- 采用右递归的超简单八皇后解决,采用递归皇后,凡是线
- Python HTMLParser模块,pythonhtmlparser,HTMLParser是p
- Python 生肖和星座计算函数,python生肖,def chinese_
- Django 利用url来控制登录,django利用url登录,1. from djan
- Python PIL批量处理处理图片,,图片太大了,上百张图用
- Python 简单的备份文件脚本,python备份脚本,#! /usr/bin/
- Python 神经网络调教程序,python神经网络调教,import ran
- Python 代码行数统计程序,python行数统计程序,import sys
评论关闭