python 连接mysql

Python连接MySQL  

闲话少说,看代码:

#!/usr/bin/env python
# -*-coding:UTF-8-*-                        #这一句告诉python用UTF-8编码
#=========================================================================
#
# NAME: Python MySQL test
#
# AUTHOR: yuzebin : yuzebin#gmail.com
# DATE  : 2004-12-28
#
# COMMENT: 这是一个python连接mysql的例子
#
#=========================================================================

"""
 ***** This is a MySQL test *****
 
 select:
  conn=Connection()
  conn.select_db('test')
  cur=conn.cursor()
  cur.execute('select * from user')
  cur.scroll(0)
  row1=cur.fetchone()
  row1[0]
  row1[1]
  row1[2]
  
 insert:
  cur.execute('insert into user (name,passwd) values(\'benyur\',\'12345\')')
  cur.insert_id()
  
 update:
  cur.execute('update user set passwd=\'123456\' where name=\'benyur\'')
  
 delete:
  cur.execute('delete from user where id=2')
 
 **********************************
"""
#以上““““““中间的部分就是本模块的__doc__的内容

from MySQLdb import *                    #导入MySQLdb模块

def conn():                                      #定义conn函数 
 conn=Connection()                          #打开连接
 conn.select_db('test')                       #选择数据库
 cur=conn.cursor()                           #取得游标
 cur.execute('select * from user')      #执行查询语句
 cur.scroll(0)                                    #滚动游标到头
 row1=cur.fetchone()                        #取得一行,row1是一个列表
 row1[0]
 row1[1]
 row1[2]

def usage():                                   #定义打印用法函数
 print __doc__                                #打印内部属性__doc__,即上面的““““““中间的部分

if __name__=='__main__':             #如果是主程序运行(不是导入模块)
 usage()                                        #打印用法


MySQLdb下载地址:http://sourceforge.net/projects/mysql-python/
下载解压缩后放到%Python_HOME%\Lib\site-packages目录中,python会自动找到此包。
MySQLdb基本上是MySQL C API的Python版,遵循Python Database API Specification v2.0。

来源:http://blog.csdn.net/Benyur/archive/2004/12/29/233222.aspx

posted @ 2008-04-13 22:35  曹振华  阅读(2405)  评论(0编辑  收藏  举报