Python连接MySQL
1。在http://sourceforge.net/projects/mysql-python/下载,连接所需要的包,MysqlDB。最新的版本是1.2.1_p2(for *NIX)或者1.2.0(for i386),我用的是i386版的,以下都以1.2.0为例。
2。下载后安装,会自动找到你Python的安装目录,装在%Python_HOME%Libsite-packages目录中。
3。程序实例:
- 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)
5。增删改的例子
insert:
cur.execute('insert into user (name,passwd) values('sparezgw','asdfasdf')')
cur.insert_id()
cur.insert_id()
update:
cur.execute('update user set passwd='asdfasdf' where name='sparezgw'')
delete:
cur.execute('delete from user where id=2')
没有评论▼