首页 > 编程 > Python > 正文

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

2019-11-08 03:05:03
字体:
来源:转载
供稿:网友

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

首先要安装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()
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表