python操作mysql
#测试模块安装 # -*- coding: UTF-8 -*- import MySQLdb print MySQLdb #打印正常安装成功
测试连接mysql
# -*- coding: UTF-8 -*- import MySQLdb # print MySQLdb conn = MySQLdb.Connect(host='127.0.0.1',port=3306,user='username',passwd='pwd',db='your_db',charset='utf8') cursor = conn.cursor() print conn print cursor cursor.close() conn.close() #输出正常
查询数据测试
#!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb conn = MySQLdb.Connect(host='xx',port=3306,user='xx',passwd='xx',db='xx',charset='utf8') cursor = conn.cursor() sql = 'select * from user' cursor.execute(sql) #所有行数 print cursor.rowcount #指针所在位置取一行 rs = cursor.fetchone() print rs #下面三行 rs = cursor.fetchmany(3) print rs #余下所有 rs = cursor.fetchall() print rs cursor.close() conn.close()
#事务部分 try: cursor.execute(insert_sql) print cursor.rowcount cursor.execute(delete_sql) print cursor.rowcount conn.commit() exception Exception as e: print e conn.rollback()