찾다
백엔드 개발파이썬 튜토리얼Python에서 MySQL을 작동하는 방법은 무엇입니까?

Python에서 MySQL을 작동하는 방법은 무엇입니까?

Apr 13, 2023 pm 09:13 PM
mysqlpython데이터 베이스

Python에서 MySQL을 작동하는 방법은 무엇입니까?

1. Python 운영 데이터베이스 소개

Python의 표준 데이터베이스 인터페이스는 개발자에게 데이터베이스 응용 프로그래밍 인터페이스를 제공하는 Python DB-API입니다. Python 데이터베이스 인터페이스는 다양한 데이터베이스를 지원하므로 프로젝트에 적합한 데이터베이스를 선택할 수 있습니다.

  • GadFly
  • mSQL
  • MySQL
  • PostgreSQL
  • Microsoft SQL Server 2000
  • Informix
  • Interbase
  • Oracle
  • S ybase ..

Python 데이터베이스 인터페이스 및 API를 방문하여 지원되는 데이터베이스의 자세한 목록을 볼 수 있습니다.

다른 데이터베이스에 대해 다른 DB API 모듈을 다운로드해야 합니다. 예를 들어 Oracle 데이터베이스 및 Mysql 데이터에 액세스해야 하는 경우 Oracle 및 MySQL 데이터베이스 모듈을 다운로드해야 합니다.

DB-API는 다양한 기본 데이터베이스 시스템 및 다양한 데이터베이스 인터페이스 프로그램에 대한 일관된 액세스 인터페이스를 제공하기 위해 일련의 필수 객체 및 데이터베이스 액세스 방법을 정의합니다.

Python의 DB-API는 대부분의 데이터베이스에 대한 인터페이스를 구현합니다. 이를 사용하여 각 데이터베이스에 연결한 후 동일한 방식으로 각 데이터베이스를 작동할 수 있습니다.

Python DB-API 사용 프로세스:

API 모듈 소개.

데이터베이스에 연결하세요.

SQL 문 및 저장 프로시저 실행

데이터베이스 연결을 닫습니다.

2. Python은 MySQL 모듈을 작동합니다.

Python은 주로 두 가지 방법으로 MySQL을 작동합니다.

DB 모듈(네이티브 SQL)

  • PyMySQL(python2.x/3.x 지원)
  • MySQLdb(현재 python2.0만 지원) x)

orm frameworksqlachemy

  • 2.1 pymysql 모듈이 기사는 주로 pymysql 모듈을 소개합니다. Python 드라이버, Python 언어를 사용하여 MySQL 데이터베이스를 작동해 보겠습니다.
  • pip install PyMySQL
2.2 기본 사용법

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "shuke"
# Date: 2018/5/13
import pymysql
# 创建连接
conn = pymysql.connect(host="127.0.0.1", port=3306, user='zff', passwd='zff123', db='zff', charset='utf8mb4')
# 创建游标(查询数据返回为元组格式)
# cursor = conn.cursor()
# 创建游标(查询数据返回为字典格式)
cursor = conn.cursor(pymysql.cursors.DictCursor)
# 1. 执行SQL,返回受影响的行数
effect_row1 = cursor.execute("select * from USER")
# 2. 执行SQL,返回受影响的行数,一次插入多行数据
effect_row2 = cursor.executemany("insert into USER (NAME) values(%s)", [("jack"), ("boom"), ("lucy")])# 3
# 查询所有数据,返回数据为元组格式
result = cursor.fetchall()
# 增/删/改均需要进行commit提交,进行保存
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
print(result)
"""
[{'id': 6, 'name': 'boom'}, {'id': 5, 'name': 'jack'}, {'id': 7, 'name': 'lucy'}, {'id': 4, 'name': 'tome'}, {'id': 3, 'name': 'zff'}, {'id': 1, 'name': 'zhaofengfeng'}, {'id': 2, 'name': 'zhaofengfeng02'}]
"""

2.3 새로 생성된 데이터를 가져와서 ID를 증가시킵니다

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "shuke"
# Date: 2018/5/13
import pymysql
# 创建连接
conn = pymysql.connect(host="127.0.0.1", port=3306, user='zff', passwd='zff123', db='zff', charset='utf8mb4')
# 创建游标(查询数据返回为元组格式)
cursor = conn.cursor()
# 获取新创建数据自增ID
effect_row = cursor.executemany("insert into USER (NAME)values(%s)", [("eric")])
# 增删改均需要进行commit提交
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
new_id = cursor.lastrowid
print(new_id)
"""
8
"""

2.4 Query 작업

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "shuke"
# Date: 2018/5/13
import pymysql
# 创建连接
conn = pymysql.connect(host="127.0.0.1", port=3306, user='zff', passwd='zff123', db='zff', charset='utf8mb4')
# 创建游标
cursor = conn.cursor()
cursor.execute("select * from USER")
# 获取第一行数据
row_1 = cursor.fetchone()
# 获取前n行数据
row_2 = cursor.fetchmany(3)
#
# # 获取所有数据
row_3 = cursor.fetchall()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
print(row_1)
print(row_2)
print(row_3)
⚠️ 데이터를 가져올 때 커서.scroll(num, mode)을 사용하여 이동할 수 있습니다. 커서 위치, 예:

cursor.scroll(1,mode='relative') # 현재 위치를 기준으로 이동

cursor.scroll(2,mode='absolute') # 절대 위치를 기준으로 이동

2.5 SQL 주입 방지

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "shuke"
# Date: 2018/5/13
import pymysql
# 创建连接
conn = pymysql.connect(host="127.0.0.1", port=3306, user='zff', passwd='zff123', db='zff', charset='utf8mb4')
# 创建游标
cursor = conn.cursor()
# 存在sql注入情况(不要用格式化字符串的方式拼接SQL)
sql = "insert into USER (NAME) values('%s')" % ('zhangsan',)
effect_row = cursor.execute(sql)
# 正确方式一
# execute函数接受一个元组/列表作为SQL参数,元素个数只能有1个
sql = "insert into USER (NAME) values(%s)"
effect_row1 = cursor.execute(sql, ['wang6'])
effect_row2 = cursor.execute(sql, ('wang7',))
# 正确方式二
sql = "insert into USER (NAME) values(%(name)s)"
effect_row1 = cursor.execute(sql, {'name': 'wudalang'})
# 写入插入多行数据
effect_row2 = cursor.executemany("insert into USER (NAME) values(%s)", [('ermazi'), ('dianxiaoer')])
# 提交
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()

이렇게 하면 SQL 작업이 더 안전해집니다. 더 자세한 문서가 필요하면 PyMySQL 문서를 참조하세요. 그러나 이러한 SQL 데이터베이스의 구현은 동일하지 않은 것으로 보입니다. PyMySQL의 매개변수 자리 표시자는 %s와 같은 C 포맷터를 사용하는 반면, Python 자체 sqlite3 모듈의 자리 표시자는 물음표(?)인 것으로 보입니다. 따라서 다른 데이터베이스를 사용할 때에는 설명서를 주의 깊게 읽어보는 것이 좋습니다. PyMySQL 문서에 오신 것을 환영합니다

3. 데이터베이스 연결 풀
  • 위 방법에는 문제가 있는데, 이는 단일 스레드의 경우에 만족할 수 있습니다. 프로그램은 데이터베이스 작업을 완료하기 위해 자주 연결을 생성하고 해제해야 합니다. 그러면 우리 프로그램/스크립트는 멀티스레딩에서 어떤 문제가 발생할까요? 이때 이 문제를 해결하려면 데이터베이스 연결 풀을 사용해야 합니다!
  • 3.1 DBUtils 모듈
DBUtils는 Python에서 구현하는 데 사용되는 모듈입니다. 데이터베이스 연결 풀.

이 연결 풀에는 두 가지 연결 모드가 있습니다.

각 스레드에 대한 연결을 만듭니다. 스레드가 close 메소드를 호출하더라도 연결이 닫히지 않고 자체 스레드에 대한 연결 풀에 다시 넣습니다. 다시 사용하려면. 스레드가 종료되면 연결이 자동으로 닫힙니다

모든 스레드가 공유할 수 있도록 연결 풀에 대한 연결 배치 생성(권장)

3.2 모드 1

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "shuke"
# Date: 2018/5/13
from DBUtils.PersistentDB import PersistentDB
import pymysql
POOL = PersistentDB(
 creator=pymysql,# 使用链接数据库的模块
 maxusage=None,# 一个链接最多被重复使用的次数,None表示无限制
 setsession=[],# 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
 ping=0,
 # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
 closeable=False,
 # 如果为False时, conn.close() 实际上被忽略,供下次使用,在线程关闭时,才会自动关闭链接。如果为True时, conn.close()则关闭链接,那么再次调用pool.connection时就会报错,因为已经真的关闭了连接(pool.steady_connection()可以获取一个新的链接)
 threadlocal=None,# 本线程独享值得对象,用于保存链接对象,如果链接对象被重置
 host='127.0.0.1',
 port=3306,
 user='zff',
 password='zff123',
 database='zff',
 charset='utf8',
)
def func():
 conn = POOL.connection(shareable=False)
 cursor = conn.cursor()
 cursor.execute('select * from USER')
 result = cursor.fetchall()
 cursor.close()
 conn.close()
 return result
result = func()
print(result)

3.3 모드 2

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "shuke"
# Date: 2018/5/13
import time
import pymysql
import threading
from DBUtils.PooledDB import PooledDB, SharedDBConnection
POOL = PooledDB(
 creator=pymysql,# 使用链接数据库的模块
 maxconnections=6,# 连接池允许的最大连接数,0和None表示不限制连接数
 mincached=2,# 初始化时,链接池中至少创建的空闲的链接,0表示不创建
 maxcached=5,# 链接池中最多闲置的链接,0和None不限制
 maxshared=3,
 # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
 blocking=True,# 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
 maxusage=None,# 一个链接最多被重复使用的次数,None表示无限制
 setsession=[],# 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
 ping=0,
 # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
 host='127.0.0.1',
 port=3306,
 user='zff',
 password='zff123',
 database='zff',
 charset='utf8'
)
def func():
 # 检测当前正在运行连接数的是否小于最大链接数,如果不小于则:等待或报raise TooManyConnections异常
 # 否则
 # 则优先去初始化时创建的链接中获取链接 SteadyDBConnection。
 # 然后将SteadyDBConnection对象封装到PooledDedicatedDBConnection中并返回。
 # 如果最开始创建的链接没有链接,则去创建一个SteadyDBConnection对象,再封装到PooledDedicatedDBConnection中并返回。
 # 一旦关闭链接后,连接就返回到连接池让后续线程继续使用。
 conn = POOL.connection()
 # print('连接被拿走了', conn._con)
 # print('池子里目前有', POOL._idle_cache, 'rn')
 cursor = conn.cursor()
 cursor.execute('select * from USER')
 result = cursor.fetchall()
 conn.close()
 return result
result = func()
print(result)

⚠️ pymysql로 ​​인해, MySQLdb 등. threadsafety 값이 1이므로 이 모드에서 연결 풀의 스레드는 모든 스레드에서 공유되므로 스레드로부터 안전합니다. 연결 풀이 없으면 pymysql을 사용하여 데이터베이스에 연결할 때 단일 스레드 응용 프로그램에는 문제가 없습니다. 그러나 다중 스레드 응용 프로그램이 관련되면 잠금이 필요합니다. 일단 잠기면 연결이 필연적으로 대기열에 추가됩니다. .요청이 많으면 성능이 저하됩니다.
  • 3.4 잠김
  • #! /usr/bin/env python
    # -*- coding: utf-8 -*-
    # __author__ = "shuke"
    # Date: 2018/5/13
    import pymysql
    import threading
    from threading import RLock
    LOCK = RLock()
    CONN = pymysql.connect(host='127.0.0.1',
    port=3306,
    user='zff',
    password='zff123',
    database='zff',
    charset='utf8')
    def task(arg):
     with LOCK:
     cursor = CONN.cursor()
     cursor.execute('select * from USER ')
     result = cursor.fetchall()
     cursor.close()
     print(result)
    for i in range(10):
     t = threading.Thread(target=task, args=(i,))
     t.start()
  • 3.5 잠금 없음(오류 보고)
  • #! /usr/bin/env python
    # -*- coding: utf-8 -*-
    # __author__ = "shuke"
    # Date: 2018/5/13
    import pymysql
    import threading
    CONN = pymysql.connect(host='127.0.0.1',
    port=3306,
    user='zff',
    password='zff123',
    database='zff',
    charset='utf8')
    def task(arg):
     cursor = CONN.cursor()
     cursor.execute('select * from USER ')
     # cursor.execute('select sleep(10)')
     result = cursor.fetchall()
     cursor.close()
     print(result)
    for i in range(10):
     t = threading.Thread(target=task, args=(i,))
     t.start()
이때 데이터베이스에서 연결 상태를 확인할 수 있습니다. 'Threads%'와 같은 상태를 표시합니다.

4 데이터베이스 연결 풀은 다음과 함께 사용됩니다. pymsql

# cat sql_helper.py
import pymysql
import threading
from DBUtils.PooledDB import PooledDB, SharedDBConnection
POOL = PooledDB(
 creator=pymysql,# 使用链接数据库的模块
 maxconnections=20,# 连接池允许的最大连接数,0和None表示不限制连接数
 mincached=2,# 初始化时,链接池中至少创建的空闲的链接,0表示不创建
 maxcached=5,# 链接池中最多闲置的链接,0和None不限制
 #maxshared=3,# 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
 blocking=True,# 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
 maxusage=None,# 一个链接最多被重复使用的次数,None表示无限制
 setsession=[],# 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
 ping=0,
 # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
 host='192.168.11.38',
 port=3306,
 user='root',
 passwd='apNXgF6RDitFtDQx',
 db='m2day03db',
 charset='utf8'
)
def connect():
 # 创建连接
 # conn = pymysql.connect(host='192.168.11.38', port=3306, user='root', passwd='apNXgF6RDitFtDQx', db='m2day03db')
 conn = POOL.connection()
 # 创建游标
 cursor = conn.cursor(pymysql.cursors.DictCursor)
 return conn,cursor
def close(conn,cursor):
 # 关闭游标
 cursor.close()
 # 关闭连接
 conn.close()
def fetch_one(sql,args):
 conn,cursor = connect()
 # 执行SQL,并返回收影响行数
 effect_row = cursor.execute(sql,args)
 result = cursor.fetchone()
 close(conn,cursor)
 return result
def fetch_all(sql,args):
 conn, cursor = connect()
 # 执行SQL,并返回收影响行数
 cursor.execute(sql,args)
 result = cursor.fetchall()
 close(conn, cursor)
 return result
def insert(sql,args):
 """
 创建数据
 :param sql: 含有占位符的SQL
 :return:
 """
 conn, cursor = connect()
 # 执行SQL,并返回收影响行数
 effect_row = cursor.execute(sql,args)
 conn.commit()
 close(conn, cursor)
def delete(sql,args):
 """
 创建数据
 :param sql: 含有占位符的SQL
 :return:
 """
 conn, cursor = connect()
 # 执行SQL,并返回收影响行数
 effect_row = cursor.execute(sql,args)
 conn.commit()
 close(conn, cursor)
 return effect_row
def update(sql,args):
 conn, cursor = connect()
 # 执行SQL,并返回收影响行数
 effect_row = cursor.execute(sql, args)
 conn.commit()
 close(conn, cursor)
 return effect_row

PS: 정적 메소드를 사용하여 쉽게 사용할 수 있도록 클래스로 캡슐화할 수 있습니다.

위 내용은 Python에서 MySQL을 작동하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
이 기사는 51CTO.COM에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제
어레이는 파이썬으로 과학 컴퓨팅에 어떻게 사용됩니까?어레이는 파이썬으로 과학 컴퓨팅에 어떻게 사용됩니까?Apr 25, 2025 am 12:28 AM

Arraysinpython, 특히 비밀 복구를위한 ArecrucialInscientificcomputing.1) theaRearedFornumericalOperations, DataAnalysis 및 MachinELearning.2) Numpy'SimplementationIncensuressuressurations thanpythonlists.3) arraysenablequick

같은 시스템에서 다른 파이썬 버전을 어떻게 처리합니까?같은 시스템에서 다른 파이썬 버전을 어떻게 처리합니까?Apr 25, 2025 am 12:24 AM

Pyenv, Venv 및 Anaconda를 사용하여 다양한 Python 버전을 관리 할 수 ​​있습니다. 1) PYENV를 사용하여 여러 Python 버전을 관리합니다. Pyenv를 설치하고 글로벌 및 로컬 버전을 설정하십시오. 2) VENV를 사용하여 프로젝트 종속성을 분리하기 위해 가상 환경을 만듭니다. 3) Anaconda를 사용하여 데이터 과학 프로젝트에서 Python 버전을 관리하십시오. 4) 시스템 수준의 작업을 위해 시스템 파이썬을 유지하십시오. 이러한 도구와 전략을 통해 다양한 버전의 Python을 효과적으로 관리하여 프로젝트의 원활한 실행을 보장 할 수 있습니다.

표준 파이썬 어레이를 통해 Numpy Array를 사용하면 몇 가지 장점은 무엇입니까?표준 파이썬 어레이를 통해 Numpy Array를 사용하면 몇 가지 장점은 무엇입니까?Apr 25, 2025 am 12:21 AM

Numpyarrayshaveseveraladvantagesstandardpythonarrays : 1) thearemuchfasterduetoc 기반 간증, 2) thearemorememory-refficient, 특히 withlargedatasets 및 3) wepferoptizedformationsformationstaticaloperations, 만들기, 만들기

어레이의 균질 한 특성은 성능에 어떤 영향을 미칩니 까?어레이의 균질 한 특성은 성능에 어떤 영향을 미칩니 까?Apr 25, 2025 am 12:13 AM

어레이의 균질성이 성능에 미치는 영향은 이중입니다. 1) 균질성은 컴파일러가 메모리 액세스를 최적화하고 성능을 향상시킬 수 있습니다. 2) 그러나 유형 다양성을 제한하여 비 효율성으로 이어질 수 있습니다. 요컨대, 올바른 데이터 구조를 선택하는 것이 중요합니다.

실행 파이썬 스크립트를 작성하기위한 모범 사례는 무엇입니까?실행 파이썬 스크립트를 작성하기위한 모범 사례는 무엇입니까?Apr 25, 2025 am 12:11 AM

tocraftexecutablepythonscripts, 다음과 같은 비스트 프랙티스를 따르십시오 : 1) 1) addashebangline (#!/usr/bin/envpython3) tomakethescriptexecutable.2) setpermissionswithchmod xyour_script.py.3) organtionewithlarstringanduseifname == "__"

Numpy 배열은 배열 모듈을 사용하여 생성 된 배열과 어떻게 다릅니 까?Numpy 배열은 배열 모듈을 사용하여 생성 된 배열과 어떻게 다릅니 까?Apr 24, 2025 pm 03:53 PM

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

Numpy Array의 사용은 Python에서 어레이 모듈 어레이를 사용하는 것과 어떻게 비교됩니까?Numpy Array의 사용은 Python에서 어레이 모듈 어레이를 사용하는 것과 어떻게 비교됩니까?Apr 24, 2025 pm 03:49 PM

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

CTYPES 모듈은 파이썬의 어레이와 어떤 관련이 있습니까?CTYPES 모듈은 파이썬의 어레이와 어떤 관련이 있습니까?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.