当前位置:网站首页>Encapsulate the general connection and query of the project with pymysql
Encapsulate the general connection and query of the project with pymysql
2022-07-23 17:24:00 【Hall owner a Niu】
Personal profile
- Author's brief introduction : Hello everyone , I'm Daniel , New star creator of the whole stack .
- Stand by me : give the thumbs-up + Collection ️+ Leaving a message.
- Series column : Punching and kicking database
- Maxim : To be light , Because there are people who are afraid of the dark !

I found a good AI learning website a few days ago , Easy to understand , Humor and wit humor , I can't help but share it with you .
Click to jump to the website : AI learning
Catalog
Preface
A project usually needs a database , And for python This language , Except that some frames come with orm Or extended orm( image django Bring their own orm,flask You need to expand orm), Use orm There must be his advantage , But there is no doubt that you need to spend time learning this orm, Next, Daniel will take you to use pymysql Simply sub assemble a universal connection , Close and query !
pymysql Introduction and installation
PyMySQL Is in Python3.x Version for connecting MySQL A library of servers ,Python2 Use... In mysqldb.
Install at the terminal using the following instructions :
pip3 install PyMySQL
pymysql Use
import pymysql
# Open database connection ,password Password for your database ,db It's the database name
db = pymysql.connect(host="127.0.0.1",
user="root",
password=" ",
db=" ",
charset="utf8")
# Use cursor() Method to create a cursor object
cursor = db.cursor()
# Use execute() Method execution SQL Inquire about
cursor.execute("SELECT VERSION()")
# Use fetchone() Method to get a single piece of data .
data = cursor.fetchone()
print("Database version : %s " % data)
# Close database connection
db.close()
password Password for your database ,db It's the database name , Please set up your mysql database .

Pictured , I connected successfully and got the version of my database !
Method execute Carry out our sql sentence .
When getting the result of execution , You can specify the number of results obtained , The following options are available :
fetchone() # Get a piece of data of the search results
fetchmany(n) # Get search results n Data
fetchall() # Get all the data of the search results
It should be noted that , Similar to the pointer when reading a file , If in the same code , First use fetchone() Get the first data of the search result , And then use fetchmany(2) Words , The pointer will read the execution result backwards at the current position of the search result , Instead of re reading the retrieved results from the beginning .
The result obtained is tuple ., Here's the picture :

Encapsulate the general connection and query of the project
Please write the password and database by yourself
import pymysql
# Create connection
#return: Connect , The cursor
def get_conn():
# Create connection
conn = pymysql.connect(host="127.0.0.1",
user="root",
password="",
db="",
charset="utf8")
# Create cursors
cursor = conn.cursor()# The result set returned after execution is displayed in tuples by default
return conn, cursor
# Close cursor , Connect
def close_conn(conn, cursor):
cursor.close()
conn.close()
def query(sql,*args):
""" Encapsulate generic queries :param sql: :param args: :return: Return the query result ,((),(),) In the form of """
conn, cursor = get_conn()
cursor.execute(sql,args)
res = cursor.fetchall()
close_conn(conn, cursor)
return res
therefore , We only need to call query() Function is OK ,*args You can let it pass in any parameter or no parameter , It only needs sql The number of placeholders in the statement corresponds to the number of parameters !
Use as shown in the figure below 
Conclusion
As long as yours. sql Pass through ,pymsql It can also help you complete the project ! It is not necessary to use orm Oh !
If you think the blogger's writing is good , You can pay attention to the current column , Bloggers will finish this series ! You are also welcome to subscribe to other good columns of bloggers .
Series column
Soft grinding css
Hard bubble javascript
flask Framework quick start
边栏推荐
- Pymoo learning (2): Bi objective optimization problems with constraints
- 新零售电商平台怎么做?才能实现传统零售企业数字化转型?
- CSR、SSR 与 SSG
- Fundamentals of C language -- 2-6 pointers, arrays and sizeof operators
- 零基础怎么自学软件测试?十年测试老鸟最强软件测试学习路线图
- Could not load dynamic library ‘cudnn64_8.dll‘; dlerror: cudnn64_8.dll not found
- IR drop, EM, noise and antenna
- Search Binary Tree - find nodes, insert nodes, delete nodes
- 程序员最想干的三件事 |漫画
- 软件配置 | Anaconda下载、安装及环境配置和卸载
猜你喜欢

Pymoo learning (2): Bi objective optimization problems with constraints

SQL bool盲注和时间盲注详解

12张图+6K字图解ZGC垃圾回收器及调优技巧

Pymoo学习 (3):使用多目标优化找到最优解的集合

How to refine the operation of small program mall?

食品安全|爱吃烟熏食品的注意了,这些知识你知道吗

Program environment and pretreatment

AXI interconnect IP核的说明及用法

Software configuration | Anaconda download, installation, environment configuration and uninstall

搜索二叉树——寻找节点,插入节点,删除节点
随机推荐
PIP reports an error could not find a version that satisfies the... No matching distribution
食品安全|喝鲜奶可能感染结核病?带你了解什么是牛奶灭菌
来自某学生的求助,干了,闲暇能帮就帮一把!
leetcode刷题记录
Thoughts on software quality system
Pymoo learning (3): use multi-objective optimization to find the set of optimal solutions
Nodejs implements token login registration (koa2)
通用分页实现
keras——accuracy_ Score formula
What about the reason why GOM and GEE set up a black screen and the fact that individual equipment maps are not displayed?
职场3道坎:年薪30万、50万、100万
Preliminary understanding of string
Description and usage of Axi interconnect IP core
【redis入门系列】redis搭建主从服务器
[31. Maze walking (BFS)]
项目中遇到的问题及解决
在 Kotlin 中使用 Flow Builder 创建流
benthos杂记
Detailed explanation of SQL bool blind note and time blind note
七月集训(第23天) —— 字典树