Python连接MySQL
[color="#000000"]#!/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的例子
#
#========================================================================= [color="#000000"]"""
***** 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__的内容
[color="#000000"]from MySQLdb import * #导入MySQLdb模块
[color="#000000"]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]
[color="#000000"]def usage(): #定义打印用法函数
print __doc__ #打印内部属性__doc__,即上面的““““““中间的部分
[color="#000000"]if __name__=='__main__': #如果是主程序运行(不是导入模块)
usage() #打印用法
[color="#000000"]import MySQLdb
conn=MySQLdb.Connect(host='localhost',user='root',passwd='111111')
curs=conn.cursor()
try:
curs.execute('drop database etcdb')
print "database alrealdy exist,delete this database!"
except:
print "database not exist,create this database!"
pass #did not exist
curs.execute('create database etcdb')
print "create new database!"
curs.execute('use etcdb')
print "use new database"
curs.execute('create table users (name char(30),password char(20))')
print "create new table"
curs.execute('insert users values (%s,%s)',('honggou','honggou'))
curs.execute('insert users values (%s,%s)',('wurui','wurui'))
curs.execute('insert users values (%s,%s)',('mengle','mengle'))
curs.execute('insert users values (%s,%s)',('lidai','lidai'))
curs.execute('insert users values (%s,%s)',('111','111'))
print "insert values to table"
curs.execute('select * from users')
for row in curs.fetchall():
print row
curs.execute('select * from users')
colnames=[desc[0] for desc in curs.description]
while True:
print '-'*30
row=curs.fetchone()
if not row:break
for (name,value) in zip(colnames,row):
print '%s =>> %s' % (name,value)
conn.commit()
[color="#000000"]