python连接mysql数据库[复制链接] xieao 电梯直达 1# 发表于 2008-12-6 12:39:00 | 只看该作者 | 倒序浏览 1. 平台及版本 WkFTechFeel linux 内核2.6,gcc 3.4.4,glibc 2.4 WkFTechFeel python 2.4.3 WkFTechFeel mysql 5.0.19 WkFTechFeel mysql-python 1.2.1-p2 WkFTechFeel 2. 安装mysql-python WkFTechFeel tar xvfz MySQL-python-1.2.1_p2.tar.gz WkFTechFeel cd MySQL-python-1.2.1_p2 WkFTechFeel python setup.py build WkFTechFeel python setup.py install WkFTechFeel WkFTechFeel 3. 使用 WkFTechFeel import MySQLdb WkFTechFeel 3.1. 连接 WkFTechFeel conn = MySQLdb.Connection(host, user, password, dbname) WkFTechFeel 3.2. 选择数据库 WkFTechFeel conn.select_db(’database name’) WkFTechFeel 3.3. 获得cursor WkFTechFeel cur = conn.cursor() WkFTechFeel 3.4. cursor位置设定 WkFTechFeel cur.scroll(int, mode) WkFTechFeel mode可为相对位置或者绝对位置,分别为relative和absolute。 WkFTechFeel WkFTechFeel 3.5. select WkFTechFeel cur.execute(‘select clause’) WkFTechFeel 例如 WkFTechFeel cur.execute(‘select * from mytable’) WkFTechFeel WkFTechFeel row = cur.fetchall() WkFTechFeel 或者: WkFTechFeel row1 = cur.fetchone() WkFTechFeel 3.6. insert WkFTechFeel cur.execute(‘inset clause’) WkFTechFeel 例如 WkFTechFeel cur.execute(‘insert into table (row1, row2) values (\’111\’, \’222\’)’) WkFTechFeel WkFTechFeel conn.commit() WkFTechFeel WkFTechFeel 3.7. update WkFTechFeel cur.execute(‘update clause’) WkFTechFeel 例如 WkFTechFeel cur.execute(“update table set row1 = ‘’ where row2 = ‘row2 ‘ ”) WkFTechFeel WkFTechFeel conn.commit() WkFTechFeel WkFTechFeel 3.8. delete WkFTechFeel cur.execute(‘delete clause’) WkFTechFeel 例如 WkFTechFeel cur.execute(“delete from table where row1 = ‘row1’ ”) WkFTechFeel WkFTechFeel conn.commit() WkFTechFeel