安装引入模块
安装mysql模块
sudo apt-get install python-mysql

在文件中引入模块
import Mysqldb

Connection对象
用于建立与数据库的连接
创建对象:调用connect()方法
conn=connect(参数列表)
参数host:连接的mysql主机,如果本机是’localhost’
参数port:连接的mysql主机的端口,默认是3306
参数db:数据库的名称
参数user:连接的用户名
参数password:连接的密码
参数charset:通信采用的编码方式,默认是’gb2312’,要求与数据库创建时指定的编码一致,否则中文会乱码

对象的方法
close()关闭连接
commit()事务,所以需要提交才会生效
rollback()事务,放弃之前的操作
cursor()返回Cursor对象,用于执行sql语句并获得结果
Cursor对象

执行sql语句
创建对象:调用Connection对象的cursor()方法
cursor1=conn.cursor()

对象的方法
close()关闭
execute(operation [, parameters ])执行语句,返回受影响的行数
fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组
next()执行查询语句时,获取当前行的下一行
fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回
scroll(value[,mode])将行指针移动到某个位置
mode表示移动的方式
mode的默认值为relative,表示基于当前行移动到value,value为正则向下移动,value为负则向上移动
mode的值为absolute,表示基于第一条数据的位置,第一条数据的位置为0

对象的属性
rowcount只读属性,表示最近一次execute()执行后受影响的行数
connection获得当前连接对象

增加
创建testInsert.py文件,向学生表中插入一条数据

#encoding=utf-8
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)
cs1=conn.cursor()
count=cs1.execute(“insert into students(sname) values(‘张良’)”)
print count
conn.commit()
cs1.close()
conn.close()
except Exception,e:
print e.message
xxxxxxxxxx12 1#encoding=utf-82import MySQLdb3try:4 conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)5 cs1=conn.cursor()6 count=cs1.execute(“insert into students(sname) values(‘张良’)”)7 print count8 conn.commit()9 cs1.close()10 conn.close()11except Exception,e:12 print e.message

修改
创建testUpdate.py文件,修改学生表的一条数据

#encoding=utf-8
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)
cs1=conn.cursor()
count=cs1.execute(“update students set sname=‘刘邦’ where id=6”)
print count
conn.commit()
cs1.close()
conn.close()
except Exception,e:
print e.message
xxxxxxxxxx12 1#encoding=utf-82import MySQLdb3try:4 conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)5 cs1=conn.cursor()6 count=cs1.execute(“update students set sname=‘刘邦’ where id=6”)7 print count8 conn.commit()9 cs1.close()10 conn.close()11except Exception,e:12 print e.message

删除
创建testDelete.py文件,删除学生表的一条数据

#encoding=utf-8
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)
cs1=conn.cursor()
count=cs1.execute(“delete from students where id=6”)
print count
conn.commit()
cs1.close()
conn.close()
except Exception,e:
print e.message
xxxxxxxxxx12 1#encoding=utf-82import MySQLdb3try:4 conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)5 cs1=conn.cursor()6 count=cs1.execute(“delete from students where id=6”)7 print count8 conn.commit()9 cs1.close()10 conn.close()11except Exception,e:12 print e.message

sql语句参数化
创建testInsertParam.py文件,向学生表中插入一条数据

#encoding=utf-8
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)
cs1=conn.cursor()
sname=raw_input(“请输入学生姓名:”)
params=[sname]
count=cs1.execute(‘insert into students(sname) values(%s)’,params)
print count
conn.commit()
cs1.close()
conn.close()
except Exception,e:
print e.message
xxxxxxxxxx14 1#encoding=utf-82import MySQLdb3try:4 conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)5 cs1=conn.cursor()6 sname=raw_input(“请输入学生姓名:”)7 params=[sname]8 count=cs1.execute(‘insert into students(sname) values(%s)’,params)9 print count10 conn.commit()11 cs1.close()12 conn.close()13except Exception,e:14 print e.message

其它语句
cursor对象的execute()方法,也可以用于执行create table等语句
建议在开发之初,就创建好数据库表结构,不要在这里执行

查询一行数据
创建testSelectOne.py文件,查询一条学生信息

#encoding=utf8
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)
cur=conn.cursor()
cur.execute(‘select * from students where id=7’)
result=cur.fetchone()
print result
cur.close()
conn.close()
except Exception,e:
print e.message
xxxxxxxxxx12 1#encoding=utf82import MySQLdb3try:4 conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)5 cur=conn.cursor()6 cur.execute(‘select * from students where id=7’)7 result=cur.fetchone()8 print result9 cur.close()10 conn.close()11except Exception,e:12 print e.message

查询多行数据
创建testSelectMany.py文件,查询一条学生信息

#encoding=utf8
import MySQLdb
try:
conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)
cur=conn.cursor()
cur.execute(‘select * from students’)
result=cur.fetchall()
print result
cur.close()
conn.close()
except Exception,e:
print e.message
xxxxxxxxxx12 1#encoding=utf82import MySQLdb3try:4 conn=MySQLdb.connect(host=‘localhost’,port=3306,db=‘test1’,user=‘root’,passwd=‘mysql’,charset=‘utf8’)5 cur=conn.cursor()6 cur.execute(‘select * from students’)7 result=cur.fetchall()8 print result9 cur.close()10 conn.close()11except Exception,e:12 print e.message

封装
观察前面的文件发现,除了sql语句及参数不同,其它语句都是一样的
创建MysqlHelper.py文件,定义类

#encoding=utf8
import MySQLdb

class MysqlHelper():
def init(self,host,port,db,user,passwd,charset=‘utf8’):
self.host=host
self.port=port
self.db=db
self.user=user
self.passwd=passwd
self.charset=charset

def connect(self):self.conn=MySQLdb.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset)self.cursor=self.conn.cursor()def close(self):self.cursor.close()self.conn.close()def get_one(self,sql,params=()):result=Nonetry:self.connect()self.cursor.execute(sql, params)result = self.cursor.fetchone()self.close()except Exception, e:print e.messagereturn resultdef get_all(self,sql,params=()):list=()try:self.connect()self.cursor.execute(sql,params)list=self.cursor.fetchall()self.close()except Exception,e:print e.messagereturn listdef insert(self,sql,params=()):return self.__edit(sql,params)def update(self, sql, params=()):return self.__edit(sql, params)def delete(self, sql, params=()):return self.__edit(sql, params)def __edit(self,sql,params):count=0try:self.connect()count=self.cursor.execute(sql,params)self.conn.commit()self.close()except Exception,e:print e.messagereturn count

xxxxxxxxxx61 1#encoding=utf82import MySQLdb3​4class MysqlHelper():5 def init(self,host,port,db,user,passwd,charset=‘utf8’):6 self.host=host7 self.port=port8 self.db=db9 self.user=user10 self.passwd=passwd11 self.charset=charset12​13 def connect(self):14 self.conn=MySQLdb.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset)15 self.cursor=self.conn.cursor()16​17 def close(self):18 self.cursor.close()19 self.conn.close()20​21 def get_one(self,sql,params=()):22 result=None23 try:24 self.connect()25 self.cursor.execute(sql, params)26 result = self.cursor.fetchone()27 self.close()28 except Exception, e:29 print e.message30 return result31​32 def get_all(self,sql,params=()):33 list=()34 try:35 self.connect()36 self.cursor.execute(sql,params)37 list=self.cursor.fetchall()38 self.close()39 except Exception,e:40 print e.message41 return list42​43 def insert(self,sql,params=()):44 return self.__edit(sql,params)45​46 def update(self, sql, params=()):47 return self.__edit(sql, params)48​49 def delete(self, sql, params=()):50 return self.__edit(sql, params)51​52 def __edit(self,sql,params):53 count=054 try:55 self.connect()56 count=self.cursor.execute(sql,params)57 self.conn.commit()58 self.close()59 except Exception,e:60 print e.message61 return count

添加
创建testInsertWrap.py文件,使用封装好的帮助类完成插入操作

#encoding=utf8
from MysqlHelper import *

sql=‘insert into students(sname,gender) values(%s,%s)’
sname=raw_input(“请输入用户名:”)
gender=raw_input(“请输入性别,1为男,0为女”)
params=[sname,bool(gender)]

mysqlHelper=MysqlHelper(‘localhost’,3306,‘test1’,‘root’,‘mysql’)
count=mysqlHelper.insert(sql,params)
if count1:
print ‘ok’
else:
print ‘error’
xxxxxxxxxx14 1#encoding=utf82from MysqlHelper import *3​4sql='insert into students(sname,gender) values(%s,%s)'5sname=raw_input(“请输入用户名:”)6gender=raw_input(“请输入性别,1为男,0为女”)7params=[sname,bool(gender)]8​9mysqlHelper=MysqlHelper(‘localhost’,3306,‘test1’,‘root’,‘mysql’)10count=mysqlHelper.insert(sql,params)11if count1:12 print 'ok’13else:14 print ‘error’

查询一个
创建testGetOneWrap.py文件,使用封装好的帮助类完成查询最新一行数据操作

#encoding=utf8
from MysqlHelper import *

sql=‘select sname,gender from students order by id desc’

helper=MysqlHelper(‘localhost’,3306,‘test1’,‘root’,‘mysql’)
one=helper.get_one(sql)
print one
xxxxxxxxxx8 1#encoding=utf82from MysqlHelper import *3​4sql='select sname,gender from students order by id desc’5​6helper=MysqlHelper(‘localhost’,3306,‘test1’,‘root’,‘mysql’)7one=helper.get_one(sql)8print one

实例:用户登录
创建用户表userinfos
表结构如下
id
uname
upwd
isdelete
注意:需要对密码进行加密
如果使用md5加密,则密码包含32个字符
如果使用sha1加密,则密码包含40个字符,推荐使用这种方式

create table userinfos(
id int primary key auto_increment,
uname varchar(20),
upwd char(40),
isdelete bit default 0
);
xxxxxxxxxx6 1create table userinfos(2id int primary key auto_increment,3uname varchar(20),4upwd char(40),5isdelete bit default 06);

加入测试数据
插入如下数据,用户名为123,密码为123,这是sha1加密后的值
insert into userinfos values(0,‘123’,‘40bd001563085fc35165329ea1ff5c5ecbdbbeef’,0);
接收输入并验证
创建testLogin.py文件,引入hashlib模块、MysqlHelper模块
接收输入
根据用户名查询,如果未查到则提示用户名不存在
如果查到则匹配密码是否相等,如果相等则提示登录成功
如果不相等则提示密码错误

#encoding=utf-8
from MysqlHelper import MysqlHelper
from hashlib import sha1

sname=raw_input(“请输入用户名:”)
spwd=raw_input(“请输入密码:”)

s1=sha1()
s1.update(spwd)
spwdSha1=s1.hexdigest()

sql=“select upwd from userinfos where uname=%s”
params=[sname]

sqlhelper=MysqlHelper(‘localhost’,3306,‘test1’,‘root’,‘mysql’)
userinfo=sqlhelper.get_one(sql,params)
if userinfo==None:
print ‘用户名错误’
elif userinfo[0]spwdSha1:
print ‘登录成功’
else:
print ‘密码错误’
​x 1#encoding=utf-82from MysqlHelper import MysqlHelper3from hashlib import sha14​5sname=raw_input(“请输入用户名:”)6spwd=raw_input(“请输入密码:”)7​8s1=sha1()9s1.update(spwd)10spwdSha1=s1.hexdigest()11​12sql="select upwd from userinfos where uname=%s"13params=[sname]14​15sqlhelper=MysqlHelper(‘localhost’,3306,‘test1’,‘root’,‘mysql’)16userinfo=sqlhelper.get_one(sql,params)17if userinfoNone:18 print '用户名错误’19elif userinfo[0]==spwdSha1:20 print '登录成功’21else:22 print ‘密码错误’
想学习交流,视频资源等,推荐群:C++大学技术协会:145655849

如何使用Python操作MySQL数据库相关推荐

  1. python操作mysql数据库的常用方法使用详解

    python操作mysql数据库 1.环境准备: Linux 安装mysql: apt-get install mysql-server 安装python-mysql模块:apt-get instal ...

  2. Python操作mySql数据库封装类

    这是自己在做项目过程中,整理封装的操作mysql数据库封装类,自己可以修改下使用,节省大量时间. myGlobal.py # -*- coding: utf-8 -*-global globalLis ...

  3. python操作mysql数据库(增、删、改、查)_python对 MySQL 数据库进行增删改查的脚本...

    # -*- coding: utf-8 -*- import pymysql import xlrd # import codecs #连接数据库 conn = pymysql.connect(hos ...

  4. python 天气预报 mysql_python + docker, 实现天气数据 从FTP获取以及持久化(二)-- python操作MySQL数据库...

    前言 在这一节中,我们主要介绍如何使用python操作MySQL数据库. 准备 MySQL数据库使用的是上一节中的docker容器 "test-mysql". Python 操作 ...

  5. python操作mysql中的表_带你了解什么是Python操作MySQL数据库

    写这篇文章主要是为了介绍Python操作MySQL数据库,并结合相应的实例带你更加深入了解.文中的代码实例很详细,对大家有一定的参考学习价值. 1.什么是pymysql? PyMySQL是在Pytho ...

  6. python操作mysql数据库练习

    python操作mysql数据库练习 本次练习是在windows下,mysql版本为5.7,python版本为2.7.5,集成环境为pycharm. 创建表时,enign在innodb下支持事务,其他 ...

  7. imooc的疯狂的蚂蚁的课程《Python操作MySQL数据库》 python3+pymysql模块来操作mysql数据库

    以下代码为imooc的疯狂的蚂蚁的课程<Python操作MySQL数据库>的python3版本的代码,使用的是pymysql模块来操作mysql数据库,代码与原课程有所改动,注意运行时需要 ...

  8. python操作mysql数据库用到的fetchone()函数和fetchall()函数

    在用python操作mysql数据库时,碰到了下面这两个函数,标记一下: fetchone() : 返回单个的元组,也就是一条记录(row),如果没有结果 则返回 None fetchall() : ...

  9. python操作mysql数据库实现增删改查

    Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数据库,你可以选择适合你项目的数据库: ...

  10. 4000字,详解 Python 操作 MySQL 数据库!

    作者 | 黄伟呢 出品 | 数据分析与统计学之美 本文的重点,就是教会大家,如何用Python来操作MySQL数据库. 1. 通用步骤 其实,这里有一个通用步骤,都是写死了的,大家照做就行. # 1. ...

最新文章

  1. atmega8 例程:T1定时器 快速PWM
  2. Session与Cookie
  3. arduino自带程序_arduino代码运行时间测试函数,代码性能运行时间测试方法
  4. Java—Set集合详解(HashSet/LinkedHashSet/TreeSet/EnumSet)
  5. spring cloud config client refresh过程
  6. 删除linux系统中的eth0.bak与多余的网卡
  7. 138. Copy List with Random Pointer
  8. Delphi十进制和十六进制互转
  9. DispatchAction
  10. 统信UOS家庭版使用体验
  11. 优化神器 beamoff
  12. Unity编辑器拓展--Hierarchy拓展
  13. 高效能人士的七个习惯读后感与总结概括-(第四章)
  14. 特征选择方法-统计方法
  15. 职业四象限,分分钟定位你的方向
  16. [科幻]Java版三体中黑暗森林法则的猜想
  17. Matlab 查阅、读取nc数据
  18. 18北大考研经验贴汇总
  19. 关于远程连接挂载磁盘的理解(.bat文件、批处理)
  20. 仿 IOS 打造一个全局通用的对话框

热门文章

  1. java编译时文件是什么,JAVA编译出现 进行语法解释时已抵达文件结尾 是什么意思?...
  2. python的底层实现,Python封装底层实现原理详解(通俗易懂)
  3. 情绪调节的自适应_如何做好情绪的管理者
  4. 澳洲虚拟主机空间_澳洲空间|澳洲虚拟主机|澳洲主机|澳洲虚拟空间-万纵科技 www.xmwzidc.cn...
  5. 4怎么修边_亦木良品阻燃板怎么样
  6. QT学习笔记(十三):绘制图像
  7. Struts2基础知识(三)
  8. 【每日SQL打卡】​​​​​​​​​​​​​​​DAY 6丨统计各专业学生人数【难度中等】
  9. 开源 Python网络爬虫框架 Scrapy
  10. Spring Data JPA 从入门到精通~自定义实现Repository