当前位置:网站首页>[note] on May 27, 2022, MySQL is operated through pychart
[note] on May 27, 2022, MySQL is operated through pychart
2022-06-30 03:39:00 【Sprite. Nym】
1. adopt pycharm insert data
RIGHT Example:
# example01 - Connect MySQL Database inserts data
# SQL Injection - SQL Injection attack
# Experience : You must not be able to use string splicing or formatting to assemble dynamic SQL, Or you'll face it SQL Injection attack .
import pymysql
from pymysql.cursors import Cursor
no = input(' Please enter the department number :')
name = input(' Please enter the Department name :')
location = input(' Please enter the Department Address :')
# 1. Create connection
conn = pymysql.connect(host='localhost', port=3306,
user='guest', password='guest.618',
database='hrs', charset='utf8mb4')
try:
# 2. Get cursor object
with conn.cursor() as cursor: # type: Cursor
# 3. Execute through cursor objects SQL sentence
affected_rows = cursor.execute(
'select dno from tb_dept where dno = (%s)',
(no,)
)
if affected_rows == 0:
affected_rows = cursor.execute(
'insert into tb_dept (dno, dname, dloc) '
'values (%s, %s, %s)',
(no, name, location)
)
if affected_rows == 1:
print(' Department added successfully !!!')
else:
print(' Department already exists ')
# 4. Manual submission ( Let the previous operation take effect )
conn.commit()
except pymysql.MySQLError as err:
# 4. Manual rollback ( Undo the previous operation )
conn.rollback()
print(err)
finally:
# 5. Close the connection
conn.close()
Common mistakes :
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-sfyhL76v-1653644986252)(C:\Users\HP\AppData\Roaming\Typora\typora-user-images\image-20220527091525487.png)]](/img/6a/9e4f00a09348f9358b6a533bdeba7a.png)


2. adopt pycharm Delete data
RIGHT Example:
# example02 - Connect MySQL Database delete data
import pymysql
from pymysql.cursors import Cursor
no = input(' Please enter the department number :')
# 1. Create connection
conn = pymysql.connect(host='localhost', port=3306,
user='guest', password='guest.618',
database='hrs', charset='utf8mb4')
try:
# 2. Get cursor object
with conn.cursor() as cursor: # type: Cursor
# 3. Execute through cursor objects SQL sentence
affected_rows = cursor.execute(
'select dno from tb_dept where dno = (%s)',
(no,)
)
if affected_rows == 0:
print(' Already deleted ')
else:
affected_rows = cursor.execute(
'delete from tb_dept where dno = (%s) ',
(no,)
)
if affected_rows == 1:
print(' Delete Department succeeded !!!')
# 4. Manual submission ( Let the previous operation take effect )
conn.commit()
except pymysql.MySQLError as err:
# 4. Manual rollback ( Undo the previous operation )
conn.rollback()
print(err)
finally:
# 5. Close the connection
conn.close()
3. adopt pycharm Change data
RIGHT Example:
# example03 - Connect MySQL Database changes data
import pymysql
from pymysql.cursors import Cursor
no = input(' Please enter the department number :')
name = input(' Please enter the Department name :')
location = input(' Please enter the Department Address ')
# 1. Create connection
conn = pymysql.connect(host='localhost', port=3306,
user='guest', password='guest.618',
database='hrs', charset='utf8mb4')
try:
# 2. Get cursor object
with conn.cursor() as cursor: # type: Cursor
# 3. Execute through cursor objects SQL sentence
affected_rows = cursor.execute(
'update tb_dept set dname = %s, dloc = %s where dno = %s',
(name, location, no)
)
if affected_rows == 1:
print(' The update is successful ')
# 4. Manual submission ( Let the previous operation take effect )
conn.commit()
except pymysql.MySQLError as err:
# 4. Manual rollback ( Undo the previous operation )
conn.rollback()
print(err)
finally:
# 5. Close the connection
conn.close()
4. adopt pycharm Check data
# example04 - Connect MySQL Check the data in the database
import pymysql
import csv
from pymysql.cursors import Cursor, DictCursor
f = open(' The employee table .csv', 'w', encoding='utf-8', newline='')
writer = csv.writer(f)
writer.writerow([' Employee number ', ' Employee name ', ' Employee position ', ' Employee supervisor ', ' Employee's monthly salary ', ' Employee bonus ', ' Department No '])
# 1. Create connection
conn = pymysql.connect(host='localhost', port=3306,
user='guest', password='guest.618',
database='hrs', charset='utf8mb4')
try:
# 2. Get cursor object
with conn.cursor() as cursor: # type: Cursor
# 3. Execute through cursor objects SQL sentence
affected_rows = cursor.execute(
'select eno, ename, job, mgr, sal, comm, dno from tb_emp'
)
# 4. Grab data through cursor objects
while data := cursor.fetchone():
writer.writerow(data)
except pymysql.MySQLError as err:
print(err)
finally:
# 5. Close the connection
conn.close()
边栏推荐
- 2021-07-05
- Redis high concurrency distributed locks (learning summary)
- Reasons for MySQL master-slave database synchronization failure
- If you can tell whether the external stock index futures trading platform I am trading is formal and safe?
- X Book 6.97 shield unidbg calling method
- 【力扣刷题总结】数据库题目按知识点分类总结(持续更新/简单和中等题已完结)
- Implementation of property management system with ssm+ wechat applet
- 【作业】2022.5.25 MySQL 查操作2
- [note] May 23, 2022 MySQL
- 共124篇!墨天轮“高可用架构”干货文档分享(含Oracle、MySQL、PG)
猜你喜欢

hudi记录
![[Note] ab Test and Variance Analysis](/img/f2/58369a99514d37d5af335a61d0911f.jpg)
[Note] ab Test and Variance Analysis

On the optimization and use of idea

laravel9本地安裝

MySQL performance optimization (5): principle and implementation of master-slave synchronization

Redis high concurrency distributed locks (learning summary)
![[QT] QMap使用详解](/img/ee/6e71a3dc5b90d2d1b7f7d3f6b56221.png)
[QT] QMap使用详解

Practical debugging skills

QT中foreach的使用

云原生——Web实时通信技术之Websocket
随机推荐
[practical skills] how to write agile development documents
Principle of device driver
C [advanced part] C generic [need to be further supplemented: generic interfaces and instances of generic events]
UML图与List集合
How to view Tencent's 2022 school recruitment salary, the total contract of cabbage is 40W?
Half a year after joining the company, I was promoted to a management post
December2020 - true questions and analysis of C language (Level 2) in the youth level examination of the Electronic Society
Deep learning: implementation skills of deep neural network
Feign 坑
Neo4j---性能优化
Neo4j--- performance optimization
Some common functions and precautions
4-4 beauty ranking (10 points)
What are the defaults for Binding. Mode=Default for WPF controls?
Chapter 2 control structure and function (programming problem)
Tidb 6.0: rendre les GRT plus efficaces 丨 tidb Book Rush
[QT] QMap使用详解
Installation and use of yarn
[operation] MySQL query operation 2 on May 25, 2022
Integrating viewbinding and viewholder with reflection