mysql模块 环境部署: unbutu12.04 python2.7.3 mysql 5.5.40python
1.若是没有setup_tools也须要安装。mysql
软件下载地址:https://pypi.python.org/pypi/setuptools/28.8.0查找相应的的软件。sql
安装语句: python setup.py install数据库
2.须要安装MySQL-python-1.2.5.zippython2.7
软件下载地址:https://pypi.python.org/pypi/MySQL-python/1.2.5fetch
安装语句: python setup.py buildui
python setup.py installcode
若是出现报错:_mysql.c:29:20: fatal error: Python.h: No such file or directory对象
须要安装: apt_get install python-devip
3.再次执行
python setup.py build
python setup.py install
4.报错:在导入import MySQLdb时候报错:ImportError: libmysqlclient.so.18: cannot open shared object file: No such file or directory
解决方法: ln -s /usr/local/mysql/lib/libmysqlclient.so.18 /usr/lib/libmysqlclient.so.18 (32位)
ln -s /usr/local/mysql/lib/libmysqlclient.so.18 /usr/lib64/libmysqlclient.so.18 (64位)
数据库连接:
import MySQLdb #方法一 不指定数据库 db=MySQLdb.connect(host='localhost',user='root',passwd='123456') #方法二 指定数据库 db=MySQLdb.connect(host='localhost',user='root',passwd='123456',db="数据库名") cursor=db.cursor()
#建立数据库
cursor.execute("create database ceshi") print "ceshi databases created" db.close() #关闭数据库
#建立表:
db.select_db("ceshi") #选择数据库 sql="""create table student ( id int, name varchar(10), age int, class char(10) )""" cursor.execute(sql) db.close()
#表的增,删,改
db.select_db("student") #选择数据库 sql="insert into student(id,age) values (2,34)" #插入数据 sql="update student set name='wang' where id=2 " #更新数据 sql="delete from student where id=2 " #删除记录 try: cursor.execute(sql) db.commit() #提交数据库执行(×在对表进行操做的时候,须要提交数据库执行,才能成功×) except: db.rollback() db.close()
#表查找: 1.单条记录查询:
db.select_db('ceshi') sql="select count(*) from student" cursor.execute(sql) data = cursor.fetchone() #获取下一个查询结果集。结果集是一个对象 print "ten record:",data db.close()
2.多条数据查询:
db.select_db('ceshi') sql="select * from student where id < '%d'" % (10) #sql="select * from student where id = '%d'" % (10) 等价与 #sql="select * from student where id = 10" try: cursor.execute(sql) results = cursor.fetchall() #接收所有的返回结果行 for row in results: sid = row[0] sname = row[1] sage = row[2] sclass = row[3] print "id=%d,name=%s,age=%d,class=%s" % (sid,sname,sage,sclass) except: print "error: unable to fecth data" db.close()