上面好简单呀! python
程序实例: mysql
from MySQLdb import *def conn():cn=Connection('127.0.0.1','root','','test')#Connection() 函数的参数依次为# host(string, host to connect);# user(string, user to connect as);# passwd(string, password to use);# db(string, database to use)#也能够这样选择数据库#cn.select_db('test')cur=cn.cursor()cur.execute('select * from user')#设置游标的位置,不设置默认为0#cur.scroll(0)row=cur.fetchone()#查询游标位置的一条记录,返回值为元 组print row[0] #输出第一个字段内容print row[1] if __name__=='__main__':conn()4。查询时也可执行fetchall(),返回全部记录为一个元组(tuple),元组的每一个元素为每行记录;还有fetchmany(size) linux
5。增删改的例子
insert: sql
update: 数据库
cur.execute('update user set passwd='asdfasdf' where name='sparezgw'')delete: 服务器
cur.execute('delete from user where id=2')在Ubuntu上安装MySQLdb 函数
做者:NinGoo | 【转载须以超连接形式标明文章原始出处和做者信息】 测试
准备用Python写点脚本练练手,因而在Ubuntu上安装Python的MySQLdb,本觉得很简单的事,没想到还碰到几个小波折,所以记录一下以备忘。 fetch
首先须要安装Python-dev,不然后面编译MySQLdb的时候会报错,找不到头文件: ui
building '_mysql' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC
-Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3
-I/u01/mysql/include/mysql -I/usr/include/python2.6 -c _mysql.c
-o build/temp.linux-i686-2.6/_mysql.o -DUNIV_LINUX
In file included from _mysql.c:29:
pymemcompat.h:10: fatal error: Python.h: 没有那个文件或目录
compilation terminated.
error: command 'gcc' failed with exit status 1
sudo apt-get install python-dev
其次须要先安装setuptools,不然MySQLdb没法编译
ImportError: No module named setuptools
setuptools从这里下载
python setup.py build
sudo python setup.py install
从这里下载MySQLdb
修改site.cfg将mysql_config指向正确的位置
python setup.py build
sudo python setup.py install
最后还须要安装libmysqlclient-dev,不然import模块的时候会出错
ImportError: libmysqlclient_r.so.16: cannot open shared object file:
No such file or directory
sudo apt-get install libmysqlclient-dev
装完之后,来个hello world式的简单查询
#!/usr/bin/env python
import MySQLdb
db=MySQLdb.connect(host="host_name",db="mysql",user="ningoo",passwd="password")
c=db.cursor()
n=c.execute("select user,host from user")
for row in c.fetchall():
for col in row:
print col
在个人笔记本上,直接安装,无任何问题
昨天想在服务器上须要运行MYSQLDB,sudo apt-get install python-mysqldb提示安装成功,但是import MySQLdb 提示找不到此模块
sudo apt-get source python-mysqldb,想编译一下,总也不成功,总报错,google,了半天,
估计是库不全,
sudo apt-get install python-all-dev
sudo apt-get install libmysqlclient15-dev
sudo apt-get install zlib1g-dev
再从新编译 ,OK,记录在此,以避免下次有经验