与python交互

  • 在熟练使用sql语句的基础上,开始使用python语言提供的模块与mysql进行交互
  • 这是我们在工作中大事要做的事
  • 先学会sql是基础,一定要熟练编写sql语句

安装引入模块

  • 安装mysql模块
  1. .python2中使用
  2.  
  3. sudo apt-get install python-mysqldb
  • 在文件中引入模块
  1. import Mysqldb

Connection对象

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

对象的方法

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

Cursor对象

  • 执行sql语句
  • 创建对象:调用Connection对象的cursor()方法
  1. 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文件,向学生表中插入一条数据

  1. #coding=utf-
  2.  
  3. from MySQLdb import *
  4.  
  5. try:
  6. #连接数据库,localhost远程连接数据库是IP地址(如192.168.116)
  7. conn=connect(host='localhost',port=,db='py4',user='root',passwd='mysql',charset='utf8')
  8. cursors1=conn.cursor()
  9.  
  10. #sql语句
  11. sql='insert into students(name) values("小胡")'
  12. #执行sql
  13. cursors1.execute(sql)
  14.  
  15. #提交事物
  16. conn.commit()
  17. #关闭游标
  18. cursors1.close()
  19. #关闭数据库
  20. conn.close()
  21.  
  22. except Exception,e:
  23. print(e.message)

修改

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

  1. #coding=utf-
  2. import MySQLdb
  3. try:
  4. conn=MySQLdb.connect(host='localhost',port=,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 count
  8. conn.commit()
  9. cs1.close()
  10. conn.close()
  11. except Exception,e:
  12. print e.message

删除

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

  1. #coding=utf-
  2. import MySQLdb
  3. try:
  4. conn=MySQLdb.connect(host='localhost',port=,db='test1',user='root',passwd='mysql',charset='utf8')
  5. cs1=conn.cursor()
  6. count=cs1.execute("delete from students where id=6")
  7. print count
  8. conn.commit()
  9. cs1.close()
  10. conn.close()
  11. except Exception,e:
  12. print e.message

sql语句参数化,防止sql注入

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

  1. #coding=utf-
  2. import MySQLdb
  3. try:
  4. conn=MySQLdb.connect(host='localhost',port=,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 count
  10. conn.commit()
  11. cs1.close()
  12. conn.close()
  13. except Exception,e:
  14. print e.message

其它语句

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

查询一行数据

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

  1. #coding=utf8
  2. import MySQLdb
  3. try:
  4. conn=MySQLdb.connect(host='localhost',port=,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 result
  9. cur.close()
  10. conn.close()
  11. except Exception,e:
  12. print e.message

查询多行数据

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

  1. #coding=utf-
  2. import MySQLdb
  3. try:
  4. conn=MySQLdb.connect(host='localhost',port=,db='test1',user='root',passwd='mysql',charset='utf8')
  5. cur=conn.cursor()
  6. cur.execute('select * from students')
  7. result=cur.fetchall()
  8. print result
  9. cur.close()
  10. conn.close()
  11. except Exception,e:
  12. print e.message
  1.  

封装

  • 观察前面的文件发现,除了sql语句及参数不同,其它语句都是一样的
  • 创建MysqlHelper.py文件,定义类
  1. #encoding=utf8
  2. import MySQLdb
  3.  
  4. class MysqlHelper():
  5. def __init__(self,host,port,db,user,passwd,charset='utf8'):
  6. self.host=host
  7. self.port=port
  8. self.db=db
  9. self.user=user
  10. self.passwd=passwd
  11. self.charset=charset
  12.  
  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=None
  23. 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.message
  30. return result
  31.  
  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.message
  41. return list
  42.  
  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=
  54. 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.message
  61. return count

添加

  • 创建testInsertWrap.py文件,使用封装好的帮助类完成插入操作
  1. #encoding=utf8
  2. from MysqlHelper import *
  3.  
  4. sql='insert into students(sname,gender) values(%s,%s)'
  5. sname=raw_input("请输入用户名:")
  6. gender=raw_input("请输入性别,1为男,0为女")
  7. params=[sname,bool(gender)]
  8.  
  9. mysqlHelper=MysqlHelper('localhost',,'test1','root','mysql')
  10. count=mysqlHelper.insert(sql,params)
  11. if count==:
  12. print 'ok'
  13. else:
  14. print 'error'

查询一个

  • 创建testGetOneWrap.py文件,使用封装好的帮助类完成查询最新一行数据操作
  1. #encoding=utf8
  2. from MysqlHelper import *
  3.  
  4. sql='select sname,gender from students order by id desc'
  5.  
  6. helper=MysqlHelper('localhost',,'test1','root','mysql')
  7. one=helper.get_one(sql)
  8. print one
  1.  

实例:用户登录

创建用户表userinfos

  • 表结构如下

    • id
    • uname
    • upwd
    • isdelete
  • 注意:需要对密码进行加密
  • 如果使用md5加密,则密码包含32个字符
  • 如果使用sha1加密,则密码包含40个字符,推荐使用这种方式
  1. create table userinfos(
  2. id int primary key auto_increment,
  3. uname varchar(),
  4. upwd char(),
  5. isdelete bit default
  6. );

加入测试数据

  • 插入如下数据,用户名为123,密码为123,这是sha1加密后的值
  1. insert into userinfos values(,'','40bd001563085fc35165329ea1ff5c5ecbdbbeef',);

接收输入并验证

  • 创建testLogin.py文件,引入hashlib模块、MysqlHelper模块
  • 接收输入
  • 根据用户名查询,如果未查到则提示用户名不存在
  • 如果查到则匹配密码是否相等,如果相等则提示登录成功
  • 如果不相等则提示密码错误
  1. #encoding=utf-
  2. from MysqlHelper import MysqlHelper
  3. from hashlib import sha1
  4.  
  5. sname=raw_input("请输入用户名:")
  6. spwd=raw_input("请输入密码:")
  7.  
  8. s1=sha1()
  9. s1.update(spwd)
  10. spwdSha1=s1.hexdigest()
  11.  
  12. sql="select upwd from userinfos where uname=%s"
  13. params=[sname]
  14.  
  15. sqlhelper=MysqlHelper('localhost',,'test1','root','mysql')
  16. userinfo=sqlhelper.get_one(sql,params)
  17. if userinfo==None:
  18. print '用户名错误'
  19. elif userinfo[]==spwdSha1:
  20. print '登录成功'
  21. else:
  22. print '密码错误'

7.与python交互的更多相关文章

  1. 工大助手(C#与python交互)

    工大助手(爬虫--C#与python交互) 基本内容 工大助手(桌面版) 实现登陆.查成绩.计算加权平均分等功能 团队人员 13070046 孙宇辰 13070003 张帆 13070004 崔巍 1 ...

  2. Python教程(1.2)——Python交互模式

    上一节已经说过,安装完Python,在命令行输入"python"之后,如果成功,会得到类似于下面的窗口: 可以看到,结尾有3个>符号(>>>).>&g ...

  3. 区分命令行模式和Python交互模式

    命令行模式 在Windows开始菜单选择"命令提示符",就进入到命令行模式,它的提示符类似C:\> Python交互模式 在命令行模式下敲命令python,就看到类似如下的一 ...

  4. redis与python交互

    import redis #连接 r=redis.StrictRedis(host="localhost",port=6379,password="sunck" ...

  5. 命令行以及Python交互模式下python程序的编写

    一.命令行模式 在Windows开始菜单选择“命令提示符”,就进入到命令行模式,它的提示符类似C:\>: 二.Python交互模式 在命令行模式下敲命令python,就看到类似如下的一堆文本输出 ...

  6. PostgreSQL自学笔记:与python交互

    与python交互教程 原文地址:https://www.yiibai.com/html/postgresql/2013/080998.html 1. Python psycopg2 模块APIs 连 ...

  7. Python交互K线工具 K线核心功能+指标切换

    Python交互K线工具 K线核心功能+指标切换 aiqtt团队量化研究,用vn.py回测和研究策略.基于vnpy开源代码,刚开始接触pyqt,开发界面还是很痛苦,找了很多案例参考,但并不能完全满足我 ...

  8. mysql及python交互

    mysql在之前写过一次,那时是我刚刚进入博客,今天介绍一下mysql的python交互,当然前面会把mysql基本概述一下. 目录: 一.命令脚本(mysql) 1.基本命令 2.数据库操作命令 3 ...

  9. 把sublime text打造成python交互终端(windows和Ubuntu)

    作者:tongqingliu 转载请注明出处:http://www.cnblogs.com/liutongqing/p/7015958.html 把sublime text打造成python交互终端 ...

随机推荐

  1. Luogu 4556 雨天的尾巴 - 启发式合并线段树

    Solution 用$col$记录 数量最多的种类, $sum$记录 种类$col$ 的数量. 然后问题就是树上链修改, 求 每个节点 数量最多的种类. 用树上差分 + 线段树合并更新即可. Code ...

  2. django基础使用

    //创建应用 python3 manage.py startapp mysite //开启服务 python3 manage.py runserver 127.0.0.1:8080 //创建数据库命令 ...

  3. PHP5.3的编译扩展

    ./configure --prefix=/usr/local/php --enable-fastcgi --enable-zip --enable-fpm --enable-gd-native-tt ...

  4. Split Array Largest Sum LT410

    Given an array which consists of non-negative integers and an integer m, you can split the array int ...

  5. 在win8 App中,StorageFile比Path更好用

    Skip the path: stick to the StorageFile: http://blogs.msdn.com/b/wsdevsol/archive/2012/12/05/stray-f ...

  6. linux下导入导出数据库

    导入导出数据库用mysqldump命令,使用方法与mysql命令类似. 导出 导出sql(包含数据和表结构):mysqldump -uroot -p dbname > dbname.sql 导出 ...

  7. 2018.11.24 poj3261Milk Patterns(后缀数组)

    传送门 后缀数组经典题. 貌似可以用二分答案+后缀数组? 我自己yyyyyy了一个好写一点的方法. 直接先预处理出heightheightheight数组. 然后对于所有连续的k−1k-1k−1个he ...

  8. 2018.10.29 NOIP训练 数据结构(带修改莫队)

    传送门 带修莫队板题. 直接按照经典写法做就行了. 代码

  9. poj--2299(树状数组+离散化)

    一.离散化: https://www.cnblogs.com/2018zxy/p/10104393.html 二.逆序数 AC代码: #include<iostream> #include ...

  10. java正则表达式笔记

    import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntax ...