首先下载MySQLdb,地址:http://sourceforge.net/projects/mysql-python/
1. 使用
import MySQLdb
1.1. 连接
conn = MySQLdb.Connection(host, user, password, dbname)
1.2. 选择数据库,如果上面没有指定数据库,则使用此方法指定!
conn.select_db(’database name’)
1.3. 获得cursor
cur = conn.cursor()
1.4. cursor位置设定
cur.scroll(int, mode)
mode可为相对位置或者绝对位置,分别为relative和absolute。
1.5. select
cur.execute(‘select clause’)
例如
cur.execute(‘select * from mytable’)
row = cur.fetchall()
或者:
row1 = cur.fetchone()
1.6. insert
cur.execute(‘inset clause’)
例如
cur.execute("insert into user (Name, Password) values ('maggie','12345')")
conn.commit()
1.7. update
cur.execute(‘update clause’)
例如
cur.execute("update user set Name = 'eric chau' where id = 1")
conn.commit()
1.8. delete
cur.execute(‘delete clause’)
例如
cur.execute("delete from user where id = 1")
conn.commit()
完整代码:
from MySQLdb import Connect
def conn():
#conn = Connect('localhost','root','root')
#conn.select_db('eric')
conn = Connect('localhost','root','root','eric')
cur = conn.cursor()
cur.execute('select * from user')
cur.scroll(0)
row1 = cur.fetchone()
print 'id:', row1[0]
print 'name:', row1[1]
print 'password:', row1[2]
#cur.execute("insert into user (Name, Password) values ('maggie','12345')")
#cur.execute("update user set Name = 'eric chau' where id = 1")
cur.execute("delete from user where id = 11")
conn.commit()
if __name__=='__main__':
conn()
posted on 2007-09-25 13:22
周锐 阅读(893)
评论(0) 编辑 收藏 所属分类:
MySQL 、
Python