先说点题外话,偷懒了一个多月了,今天正式回归,今年要多学习点知识,一定要找个码农的工作
- 首先要安装python mysqldb模块,直接安装就行了
32位:https://pypi.python.org/pypi/MySQL-python/1.2.5
64位:http://arquivos.victorjabur.com/python/modules/MySQL-python-1.2.3.win-amd64-py2.7.exe
2.连接测试
import MySQLdb
分别为地址,用户名,密码,数据库名称
db = MySQLdb.connect("localhost","root","112233","jike" )
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print "Database version : %s " % data
db.close()
3测试查询
import MySQLdb
db = MySQLdb.connect("localhost","root","112233","jike" )
cursor = db.cursor()
cursor.execute("SELECT * from usertable")
row = int(cursor.rowcount)
print row
data=cursor.fetchall()
for da in data:
print 'userid=%s ,username=%s' %da
db.close()
结果
4
userid=2 ,username=shui
userid=3 ,username=cao
userid=4 ,username=zhao
userid=5 ,username=zhao
4.测试添加,更新,删除
默认是开启事务的,必须提交后才能更新到数据库中。
import MySQLdb
db = MySQLdb.connect("localhost","root","112233","jike" )
cursor = db.cursor()
cursor.execute("insert into usertable(userid,username) values(5,'zhao')")
print cursor.rowcount
cursor.execute("update usertable set username='cao' where userid=3")
print cursor.rowcount
cursor.execute("delete from usertable where userid=1")
print cursor.rowcount
db.commit()
db.close()