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()