pymysql模块

1.pymysql 模块

  1,安装:pip install pymysql

      pip -V 查看当前pip的版本

      pip list 查看当前python解释器环境中安装的第三方包和版本

  2.使用:

    

import pymysql
connect = connect.pymysql(
    host='localhost',
    port=3306,
    user='limi',
    password='123',
    database='db2',
    charset='utf8'
)

2 获取光标:

  cursor = conn.cursor()

3.执行sql语句:

  ret = sursor.exxecute(sql)

4.关闭:

  关闭光标

    cursor.close()

  关闭连接:

    conn.close()

5.sql注入:

  1.什么是SQL语句注入

    用户输入的内容有恶意的sql语句,后端拿到用户输入的内容不做检测直接做字符串拼接,得到一个

    和预期不一致的SQL语句

  2.怎么解决sql注入

              对用户输入的内容进行检测

    pymysql内置了这种检测,我们只需要让pymysql帮我们拼接sql语句即可.

6.pymysql的使用

  登录校验

    

import pymysql
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='limi',
    password='123',
    database='db2',
    charset='utf8'
)
cursor = conn.cursor()
sql = "select * from userinfo where  name = %s and password = %s;"
ret = cursor.execute(sql,['liming','123'])
cursor.close()
conn.close()
if ret:
    print('登录成功')
else:
    print('登录失败')

  增

import pymysql
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='limi',
    password='123',
    database='db2',
    charset='utf8'
)
cursor = conn.cursor()
sql = "insert into userinfo (name,password) values (%s,%s);"
ret = cursor.execute(sql,['litianyi','123'])
#  conn.rollback()  # 回滚
conn.commit()  # 提交
cursor.close()
conn.close()

  删

import pymysql
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='limi',
    password='123',
    database='db2',
    charset='utf8'
)
cursor = conn.cursor()
sql = "delete from userinfo where name = %s;"
ret = cursor.execute(sql,['litian'])
conn.commit()
conn.close()
cursor.close()

  改

import pymysql
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='limi',
    password='123',
    database='db2',
    charset='utf8'
)
cursor = conn.cursor()
sql = "update userinfo set password = %s where name = %s;"
ret = cursor.execute(sql,['123456','litianyi'])
conn.commit()
conn.close()
cursor.close()

  查

import pymysql
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='limi',
    password='123',
    database='db2',
    charset='utf8'
)
cursor = conn.cursor()  # 默认以元祖返回
sql = "select * from userinfo;"
cursor.execute(sql)
ret = cursor.fetchall()  # 获取所有查询回来的值
print(ret)
conn.close()
cursor.close()

  

import pymysql
conn = pymysql.connect(
    host='localhost',
    port=3306,
    user='limi',
    password='123',
    database='db2',
    charset='utf8'
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 以字典形式返回
sql = "select * from userinfo;"
cursor.execute(sql)
ret = cursor.fetchone()
print(ret)
ret = cursor.fetchmany(2)  # 两个放回值
print(ret)
conn.close()
cursor.close()

  

cursor.scroll(0,mode='absolute') 绝对位置,你让光标移动到哪里

cursor.scroll(-1,mode='relative') 相对位置,基于光标当前位置移动

 

posted @ 2018-10-08 20:38  俏如來  阅读(111)  评论(0编辑  收藏  举报