MySQL--Python操做MySQL pymysql的经常使用语法 解决mysql注入问题 pymysql必会操做

PyMySQL的安装

  • pip install PyMySQL

python链接数据库

  • 语法
import pymysql

db = pymysql.connect("数据库ip","用户","密码","数据库" ) # 打开数据库链接
cursor.execute("SELECT VERSION()")                    # 使用 execute() 方法执行 SQL 查询
data = cursor.fetchone()                              # 使用 fetchone() 方法获取单条数据
print ("Database version : %s " % data)
db.close()                                            # 关闭数据库链接
# 更多参数
import pymysql

conn = pymysql.connect(
        host='localhost', user='root', password="root",
        database='db', port=3306, charset='utf-8',
)

cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
  • 实际操做演示
    在这里插入图片描述

建立表操做

  • 通常不会在IDE建立表
  • 语法
import pymysql
 
# 打开数据库链接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 
# 使用 cursor() 方法建立一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute() 方法执行 SQL,若是表存在则删除
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
 
# 使用预处理语句建立表
sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )"""
 
cursor.execute(sql)
 
# 关闭数据库链接
db.close()

操做数据

插入数据

  • 增添回滚机制
import pymysql
 
# 打开数据库链接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 
# 使用cursor()方法获取操做游标 
cursor = db.cursor()
 
# SQL 插入语句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
   cursor.execute(sql) # 执行sql语句
   db.commit()         # 提交到数据库执行
except:
   db.rollback()       # 若是发生错误则回滚
 
# 关闭数据库链接
db.close()
  • 第二种方式
import pymysql
 
# 打开数据库链接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 
# 使用cursor()方法获取操做游标 
cursor = db.cursor()
 
# SQL 插入语句
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
       LAST_NAME, AGE, SEX, INCOME) \
       VALUES (%s, %s,  %s,  %s,  %s )" % \
       ('Mac', 'Mohan', 20, 'M', 2000)
try:
   
   cursor.execute(sql)  # 执行sql语句
   db.commit()          # 执行sql语句
except:
   db.rollback()        # 发生错误时回滚
 
# 关闭数据库链接
db.close()

查询操做

  • Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
  1. fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
  2. fetchall(): 接收所有的返回结果行.
  3. rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数
import pymysql
 
# 打开数据库链接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 
# 使用cursor()方法获取操做游标 
cursor = db.cursor()
 
# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE \
       WHERE INCOME > %s" % (1000)
try:
   
   cursor.execute(sql)# 执行SQL语句
   results = cursor.fetchall()# 获取全部记录列表
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
       # 打印结果
      print ("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \
             (fname, lname, age, sex, income ))
except:
   print ("Error: unable to fetch data")
 
# 关闭数据库链接
db.close()

更新操做

import pymysql
 
# 打开数据库链接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 
# 使用cursor()方法获取操做游标 
cursor = db.cursor()
 
# SQL 更新语句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
   cursor.execute(sql)  # 执行SQL语句
   db.commit()          # 提交到数据库执行
except
   db.rollback()        # 发生错误时回滚
 
# 关闭数据库链接
db.close()

删除操做

import pymysql
 
# 打开数据库链接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 
# 使用cursor()方法获取操做游标 
cursor = db.cursor()
 
# SQL 删除语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
try
   cursor.execute(sql)  # 执行SQL语句
   db.commit()          # 提交修改
except
   db.rollback()        # 发生错误时回滚# 关闭链接
db.close()

数据备份

数据库的逻辑备份

#语法:
# mysqldump -h 服务器 -u用户名 -p密码 数据库名 > 备份文件.sql

#示例:
#单库备份
mysqldump -uroot -p123 db1 > db1.sql
mysqldump -uroot -p123 db1 table1 table2 > db1-table1-table2.sql

#多库备份
mysqldump -uroot -p123 --databases db1 db2 mysql db3 > db1_db2_mysql_db3.sql

#备份全部库
mysqldump -uroot -p123 --all-databases > all.sql

数据恢复

#方法一:
[root@egon backup]# mysql -uroot -p123 < /backup/all.sql

#方法二:
mysql> use db1;
mysql> SET SQL_LOG_BIN=0;   #关闭二进制日志,只对当前session生效
mysql> source /root/db1.sql

事务和锁

begin;  # 开启事务
select * from emp where id = 1 for update;  # 查询id值,for update添加行锁;
update emp set salary=10000 where id = 1; # 完成更新
commit; # 提交事务

解决mysql注入问题

  • 先建表来测试
create table userinfo(
id int primary key auto_increment,
name char(12) unique not null,
password char(18) not null
);

insert into userinfo(name,password) values('min','min1234')
  • 正常执行逻辑
# 输入用户
# 输入密码
# 用户名和密码到数据库里查询数据
# 若是能查到数据 说明用户名和密码正确
# 若是查不到,说明用户名和密码不对
  • 发生sql注入问题
username = input('user >>>')
password = input('passwd >>>')
sql = "select * from userinfo where name = '%s' and password = '%s'"%(username,password)
print(sql)
用了“ -- ” mysql会注释掉--以后的sql语句
select * from userinfo where name = 'alex' ;-- and password = '792164987034';
select * from userinfo where name = 219879 or 1=1 ;-- and password = 792164987034;
select * from userinfo where name = '219879' or 1=1 ;-- and password = '792164987034';
  • 执行产生问题,并解决
import pymysql

conn = pymysql.connect(host='127.0.0.1', user='root',
                       password='123', database='day41')
cur = conn.cursor()
username = input('user >>>')
password = input('passwd >>>')
# sql = "select * from userinfo where name = %s and password = %s"
# sql = "select * from userinfo where name = '%s' and password = '%s'"%(username,password) 这样会致使sql注入问题
sql = "select * from userinfo where name=%s and password= %s"  # 这里就不需字符串的拼接了
cur.execute(sql, (username, password))  # 解决:让生成游标来帮助完成拼接
print(cur.fetchone())
cur.close()
conn.close()