新手实现Python mysql数据库增删改查

来源:互联网 发布:key-value数据库 编辑:程序博客网 时间:2024/06/08 06:38

先说点题外话,偷懒了一个多月了,今天正式回归,今年要多学习点知识,一定要找个码农的工作

  1. 首先要安装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 " % datadb.close()

3测试查询

import MySQLdbdb = MySQLdb.connect("localhost","root","112233","jike" )cursor = db.cursor()cursor.execute("SELECT  * from usertable")row = int(cursor.rowcount)print rowdata=cursor.fetchall()for da in data:    print 'userid=%s ,username=%s' %dadb.close()

结果
4
userid=2 ,username=shui
userid=3 ,username=cao
userid=4 ,username=zhao
userid=5 ,username=zhao

4.测试添加,更新,删除
默认是开启事务的,必须提交后才能更新到数据库中。

import MySQLdbdb = MySQLdb.connect("localhost","root","112233","jike" )cursor = db.cursor()cursor.execute("insert into usertable(userid,username) values(5,'zhao')")print cursor.rowcountcursor.execute("update usertable set username='cao' where userid=3")print cursor.rowcountcursor.execute("delete from  usertable where userid=1")print cursor.rowcountdb.commit()db.close()
0 0
原创粉丝点击