« »
2008-06-03Python

98

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。程序实例:

  1. from MySQLdb import *
  2. def conn():
  3. cn=Connection('127.0.0.1','root','','test')
  4. #Connection()函数的参数依次为
  5. #     host(string, host to connect);
  6. #     user(string, user to connect as);
  7. #     passwd(string, password to use);
  8. #     db(string, database to use)
  9. #也可以这样选择数据库
  10. #cn.select_db('test')
  11. cur=cn.cursor()
  12. cur.execute('select * from user')
  13. #设置游标的位置,不设置默认为0
  14. #cur.scroll(0)
  15. row=cur.fetchone()
  16. #查询游标位置的一条记录,返回值为元组
  17. print row[0] #输出第一个字段内容
  18. print row[1]
  19.  
  20. if __name__=='__main__':
  21. conn()

4。查询时也可执行fetchall(),返回所有记录为一个元组(tuple),元组的每个元素为每行记录;还有fetchmany(size)

5。增删改的例子
insert:

cur.execute('insert into user (name,passwd) values('sparezgw','asdfasdf')')
cur.insert_id()

update:

cur.execute('update user set passwd='asdfasdf' where name='sparezgw'')

delete:

cur.execute('delete from user where id=2')

 

您还可能感兴趣的内容

日志信息 »

该日志于2008-06-03 13:29由 x72 发表在Python分类下, 通告目前不可用,你可以至底部留下评论。

没有评论

发表评论 »


返回顶部