当前位置:网站首页>Mysql database learning (7) -- a brief introduction to pymysql
Mysql database learning (7) -- a brief introduction to pymysql
2022-07-07 05:23:00 【Metaphors of the world】
pymysql Basic syntax and cursor movement
import pymysql
conn = pymysql.connect(
host="127.0.0.1", # port
port=3306,
user = "root",
password="", # password , This parameter can be abbreviated as passwd=
database="test", # Name of the connected Library
charset="utf8", # Code when reading data , Do not add “-”
)
# cousor = conn.cursor() # Generate cursor , Be similar to cmd The cursor in
#
# sql = "select * from dep"
""" +------+--------------+ | id | name | +------+--------------+ | 200 | technology | | 201 | human resources | | 202 | sales | | 203 | operating | | 205 | sale | +------+--------------+ """
# res = cousor.execute(sql)
# print(res) # 5 What is printed is the sql The number of rows of data affected by the command
# print(cousor.fetchone()) # Take one of the data , Tuple form .
# In fact, the data we prefer to show is The dictionary form
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = "select * from dep"
""" +------+--------------+ | id | name | +------+--------------+ | 200 | technology | | 201 | human resources | | 202 | sales | | 203 | operating | | 205 | sale | +------+--------------+ """
res = cursor.execute(sql)
print(res) # 5 What is printed is the sql The number of rows of data affected by the command
print(cursor.fetchone()) # Take one of the data , Now it's The dictionary form .
print(cursor.fetchone()) # Execute the command , The second data in the table , The reason is that when the command is first executed , swim ( light ) mark From the position of the first data to The second data The location of , So what we get at this time is the second data , At the same time, the cursor moves to the position of the third data
# Cursor movement
cursor.scroll(1, "relative") # Move a piece of data backward relative to the current position , namely The cursor comes to the fourth data
print(cursor.fetchone()) # Article 4 data
cursor.scroll(1, "absolute") # Move from head to back A piece of data
print(cursor.fetchall()) # Take all the data , Because of this time The cursor is on the second data , So I can only get four pieces of data
sql Injection and Solutions
sql Inject
# stay test First create a user surface
create table user (
id int primary key auto_increment,
name char(16),
password varchar(32)
);
insert into user(name, password) values
("aoteman", "asd"),
("alterman", "asdzxc");
import pymysql
conn = pymysql.connect(
host="127.0.0.1",
port=3306,
database="test",
user="root",
passwd="", # Database password
charset="utf8"
)
""" +----+----------+----------+ | id | name | password | +----+----------+----------+ | 1 | aoteman | asd | | 2 | alterman | asdzxc | +----+----------+----------+ """
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# Easy login authentication
while True:
username = input("username:>>")
password = input("password:>>")
sql = "select * from user where name='%s' and password='%s' " % (username, password)
print(sql)
cursor.execute(sql)
print(cursor.fetchall())
Normal login
Abnormal login
''' In the case of abnormal login in the above demonstration , We found that One is to only know User name can realize login , And the return password of the login user One is when you don't know your account and password , To complete the login , And get the user names and passwords of all users '''
We are analyzing mysql The code executed in the above two cases is
select * from user where name='aoteman'#' and password=''
select * from user where name='' or 1=1 #' and password=''
Analyze the execution of sql Statement we will find that these abnormal login conditions are because The user skillfully used mysql The logical operation of (or) and Annotation symbols “#” Make some code exist but not execute , Thus, password verification and user name verification are skipped
Database injection is quite common , For example, when we register some accounts , Our user name and password are required to contain no special symbols in order to prevent injection .
sql The solution of injection
# The first method is to specify that special symbols cannot be included in user registration ( Poor applicability )
# The second method is used ,pymysql Methods provided by the module
sql = "select * from user where name=%s and password=%s "
cursor.execute(sql, (username, password))
In the demonstration, we can see that this method can be relatively simple to avoid sql Injection occurs
pymysql Supplementary content
''' Adding, deleting, modifying and checking Delete 、 Change 、 Adding them involves data changes , There is no way to implement directly , Need a second confirmation '''
# Execute more than one sql sentence
rows = cursor.executemany(sql, [("sekiro", "123"), ("ash", "123456")])
import pymysql
conn = pymysql.connect(
host = "127.0.0.1",
port = 3306,
user = "root",
password = "",
charset = "utf8",
database = "test518",
autocommit = True # Automatic submission
)
cursor = conn.cursor(cursor = pymysql.cursors.DictCursor)
# Add data
sql = "insert into user(name, password) values(%s, %s)"
# rows = cursor.execute(sql, ("sekiro", "123"))
# Execute more than one sql sentence
rows = cursor.executemany(sql, [("sekiro", "123"), ("ash", "123456")])
print(rows)
# conn.commit() # confirm
# modify
sql = "update user set name='ash' where id = 1"
rows = cursor.execute(sql)
print(rows)
# conn.commit() # confirm
# Delete
sql = "delete from user where id = 1"
rows = cursor.execute(sql)
print(rows)
边栏推荐
- If you want to choose some departments to give priority to OKR, how should you choose pilot departments?
- 全链路压测:影子库与影子表之争
- 漏电继电器LLJ-100FS
- PMP证书有没有必要续期?
- SQL injection HTTP header injection
- 【opencv】图像形态学操作-opencv标记不同连通域的位置
- [optimal web page width and its implementation] [recommended collection "
- Y58. Chapter III kubernetes from entry to proficiency - continuous integration and deployment (Sany)
- Development thoughts of adding new requirements in secondary development
- 创始人负债10亿,开课吧即将“下课”?
猜你喜欢
U++ game learning notes
Torch optimizer small parsing
Window scheduled tasks
Y58. Chapter III kubernetes from entry to proficiency - continuous integration and deployment (Sany)
Error: No named parameter with the name ‘foregroundColor‘
Leetcode (417) -- Pacific Atlantic current problem
SQL injection - secondary injection and multi statement injection
U++ metadata specifier learning notes
张平安:加快云上数字创新,共建产业智慧生态
Full link voltage test: the dispute between shadow database and shadow table
随机推荐
Timer create timer
Timer创建定时器
As we media, what websites are there to download video clips for free?
QT simple layout box model with spring
How can project managers counter attack with NPDP certificates? Look here
Salesforce 容器化 ISV 场景下的软件供应链安全落地实践
np. random. Shuffle and np Use swapaxis or transfer with caution
Longest non descent subsequence (LIS) (dynamic programming)
AOSP ~binder communication principle (I) - Overview
Complete code of C language neural network and its meaning
batch size设置技巧
照片选择器CollectionView
Redis如何实现多可用区?
Error: No named parameter with the name ‘foregroundColor‘
U++ metadata specifier learning notes
The founder has a debt of 1billion. Let's start the class. Is it about to "end the class"?
使用知云阅读器翻译统计遗传学书籍
磁盘监控相关命令
基于 hugging face 预训练模型的实体识别智能标注方案:生成doccano要求json格式
Vector and class copy constructors