Mysql学习日记-04pymysql的运用

Posted kangkang1999

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mysql学习日记-04pymysql的运用相关的知识,希望对你有一定的参考价值。

pymysql模块:
  pip3 install pymysql -i https://pypi.douban.com/simple
  Python模块:对数据库进行操作(SQL语句)

  1. Python实现用户登录
  2. MySQL保存数据


- 连接、关闭(游标)
- execute() -- SQL注入
- 增删改: conn.commit()
- 查 fetchone fetchall
- 获取插入数据自增ID

 

m1.py m2.py 

import pymysql

user = input("username:")
# sql 注入 username:(asdnaosjd‘ 1=1 -- )
pwd = input("password:")

conn= pymysql.connect(host="127.0.0.1", user= ‘root‘, password=‘123456‘, database=‘day4‘)
cursor = conn.cursor()

sql = "select * from exp1 where username =‘%s‘ and password = ‘%s‘"%(user, pwd,)
cursor.execute(sql)
result= cursor.fetchone()

cursor.close()
conn.close()

if result:
print("successful")
else:
print("fault")


 m2.py 

import pymysql

user = input("username:")
pwd = input("password:")

conn= pymysql.connect(host="127.0.0.1", user= ‘root‘, password=‘123456‘, database=‘day4‘)
cursor = conn.cursor()

sql = "select * from exp1 where username =‘%s‘ and password = ‘%s‘"
cursor.execute(sql,user, pwd)
result= cursor.fetchone()

cursor.close()
conn.close()

if result:
print("successful")
else:
print("fault")
m3.py
import pymysql
# 增,删,改
# user = ‘123‘
# pwd = ‘123‘
conn= pymysql.connect(host="127.0.0.1", user= ‘root‘, password=‘123456‘, database=‘day4‘)
cursor = conn.cursor()
# sql = "insert into exp1 (username, password ) value (‘ll‘,‘123‘) "
sql = "insert into exp1 (username, password ) value (%s,%s) "
# 受影响的行数
#r = cursor.execute(sql,(user, pwd,))
r = cursor.executemany(sql, [(‘wi‘,‘123‘),(‘wq‘,‘123‘)])
conn.commit()
cursor.close()
conn.close()

# 查
conn= pymysql.connect(host="127.0.0.1", user= ‘root‘, password=‘123456‘, database=‘day4‘)
cursor = conn.cursor(cursor= pymysql.cursors.DictCursor)
sql = "select * from exp1"
cursor.execute(sql)

result = cursor.fetchone()
# print( result)
# result = cursor.fetchall()
# print(result)

cursor.close()
conn.close()


# 新插入数据的自增id
conn= pymysql.connect(host="127.0.0.1", user= ‘root‘, password=‘123456‘, database=‘day4‘)
cursor = conn.cursor()

sql = "insert into exp1(username,password) value (‘1132‘ , ‘1‘)"
cursor.execute(sql)
print(cursor.lastrowid)

conn.commit()
cursor.close()
conn.close()




以上是关于Mysql学习日记-04pymysql的运用的主要内容,如果未能解决你的问题,请参考以下文章

PyMySQL的使用详解

MySQL高级之PyMySQL的使用

Python之PyMySQL的使用

(数据科学学习手札51)用pymysql来操控MySQL数据库

Python学习笔记-pyMySQL连接MySQL数据库

学习日记98:mysql之通配符