当前位置:网站首页>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)
边栏推荐
猜你喜欢
随机推荐
项目经理如何凭借NPDP证书逆袭?看这里
想要选择一些部门优先使用 OKR, 应该如何选择试点部门?
痛心啊 收到教训了
Window scheduled tasks
Longest common subsequence (LCS) (dynamic programming, recursive)
window定时计划任务
Under the trend of Micah, orebo and apple homekit, how does zhiting stand out?
漏电继电器JD1-100
Autowired注解用于List时的现象解析
Where is NPDP product manager certification sacred?
QSlider of QT control style series (I)
Array initialization of local variables
The founder has a debt of 1billion. Let's start the class. Is it about to "end the class"?
2039: [Bluebridge cup 2022 preliminaries] Li Bai's enhanced version (dynamic planning)
线程池的创建与使用
Two methods of thread synchronization
【js组件】date日期显示。
【PHP SPL笔记】
做自媒体视频剪辑,专业的人会怎么寻找背景音乐素材?
Simulate thread communication









