Python에서 MySQL 데이터베이스에 연결하는 방법은 무엇입니까?
Python 프로그램을 사용하여 MySQL 데이터베이스에 연결하는 방법은 무엇입니까?
Python 2를 사용하여 MYSQL에 3단계로 연결
1 - 설정
작업을 수행하기 전에 MySQL 드라이버를 설치해야 합니다.PHP와 달리 기본적으로 Python에는 SQLite 드라이버만 설치됩니다.가장 많이 사용되는 패키지는 MySQLdb이지만 easy_install을 사용하여 설치하는 것은 어렵습니다.MySQLdb는 Python 2만 지원합니다.
Windows 사용자의 경우 MySQLdb의 exe를 얻을 수 있습니다.
Linux, python-mysqldb(피톤-mysqldb)를 사용할 수 sudo apt-get install python-mysqldb
디스트로스의 경우), (데비안 기반 디스트로스의 경우),yum install MySQL-python
의 경우) (rpm의 경우)dnf install python-mysql
(현대 페도라 디스트로) (어 (운운운운운운운 ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( (.
Mac의 경우 Macport를 사용하여 MySQLdb를 설치할 수 있습니다.
2 - 사용방법
인스톨 후, 재기동합니다.이것은 필수는 아니지만, 문제가 생겼을 때 이 게시물에 있는 3, 4개의 질문에 대답할 수 없게 됩니다.그러니 재부팅해 주세요.
다른 패키지를 사용하는 것과 같습니다.
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="john", # your username
passwd="megajonhy", # your password
db="jonhydb") # name of the data base
# you must create a Cursor object. It will let
# you execute all the queries you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("SELECT * FROM YOUR_TABLE_NAME")
# print all the first cell of all the rows
for row in cur.fetchall():
print row[0]
db.close()
물론 수천 가지 가능성과 옵션이 있습니다.이것은 매우 기본적인 예입니다.당신은 서류를 봐야 합니다.좋은 출발점.
3 - 고도의 사용
SQL이 어떻게 작동하는지 알게 되면 ORM을 사용하여 SQL을 수동으로 쓰지 않고 Python 개체인 것처럼 테이블을 조작할 수 있습니다.Python 커뮤니티에서 가장 유명한 ORM은 SQL Chemy입니다.
꼭 사용해 보시길 권합니다. 여러분의 삶이 훨씬 더 편해질 것입니다.
최근에 파이썬의 세계에서 또 다른 보석을 발견했습니다. 피위입니다.매우 가벼운 ORM으로 셋업과 사용이 매우 쉽고 빠릅니다.SQLLchemy나 Django와 같은 큰 툴을 사용하는 것은 과도한 작업이기 때문에 소규모 프로젝트나 독립형 앱에 매우 적합합니다.
import peewee
from peewee import *
db = MySQLDatabase('jonhydb', user='john', passwd='megajonhy')
class Book(peewee.Model):
author = peewee.CharField()
title = peewee.TextField()
class Meta:
database = db
Book.create_table()
book = Book(author="me", title='Peewee is cool')
book.save()
for book in Book.filter(author="me"):
print book.title
이 예는 개봉 즉시 사용할 수 있습니다.(Peewee가 있는 것 이외에는 .pip install peewee
가 필요합니다.
다음은 Python 2만 지원하는 MySQLdb를 사용하는 한 가지 방법입니다.
#!/usr/bin/python
import MySQLdb
# Connect
db = MySQLdb.connect(host="localhost",
user="appuser",
passwd="",
db="onco")
cursor = db.cursor()
# Execute SQL select statement
cursor.execute("SELECT * FROM location")
# Commit your changes if writing
# In this case, we are only reading data
# db.commit()
# Get the number of rows in the resultset
numrows = cursor.rowcount
# Get and display one row at a time
for x in range(0, numrows):
row = cursor.fetchone()
print row[0], "-->", row[1]
# Close the connection
db.close()
MySQLdb가 필요 없지만 라이브러리를 사용할 수 있다면 MySQL 커넥터/Python을 추천합니다.http://dev.mysql.com/downloads/connector/python/
하나의 패키지(약 110k)로 순수 Python이기 때문에 시스템에 의존하지 않고 설치가 매우 간단합니다.다운로드 후 더블클릭 후 라이선스 계약을 확인하고 이동하기만 하면 됩니다.Xcode, MacPort, 컴파일, 재시작이 필요 없습니다.
다음으로 다음과 같이 접속합니다.
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='tiger',
host='127.0.0.1',
database='employees')
try:
cursor = cnx.cursor()
cursor.execute("""
select 3 from your_table
""")
result = cursor.fetchall()
print result
finally:
cnx.close()
Oracle(MySQL)은 이제 순수 Python 커넥터를 지원합니다.즉, 바이너리를 인스톨 할 필요가 없습니다.그냥 Python 라이브러리입니다.'커넥터/피톤'이라는 곡이에요
http://dev.mysql.com/downloads/connector/python/
설치 후 몇 가지 사용 예를 여기에서 볼 수 있습니다.
python에서 mysql에 액세스하기 위해 mysql 헤더를 설치하지 않으려면 MySQLdb 사용을 중지하십시오.
pymysql을 사용합니다.MySQLDB의 모든 기능을 수행하지만 외부 종속성이 없는 순수하게 Python에 구현되었습니다.이것에 의해, 모든 operating system에서의 인스톨 프로세스가 일관되고 간단하게 됩니다. pymysql
MySQLDB 및 IMHO의 대체품이 떨어진 경우 MySQLDB를 어떤 용도로도 사용할 필요가 없습니다.절대! - 하지만 그건 나뿐이야.
인스톨
pip install pymysql
바로 그거야...플레이할 준비가 되었습니다.
pymysql Github repo의 사용 예
import pymysql.cursors
import pymysql
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
또한 - 기존 코드의 MySQLdb를 빠르고 투명하게 교체
MySQLdb를 사용하는 기존 코드가 있는 경우 다음과 같은 간단한 프로세스를 통해 쉽게 pymysql로 대체할 수 있습니다.
# import MySQLdb << Remove this line and replace with:
import pymysql
pymysql.install_as_MySQLdb()
MySQLdb에 대한 후속 참조는 모두 pymysql을 투과적으로 사용합니다.
MySQLdb를 사용해 보십시오. MySQLdb는 Python 2만 지원합니다.
여기 http://www.kitebird.com/articles/pydbapi.html 에 페이지 하는 방법이 있습니다.
페이지부터:
# server_version.py - retrieve and display database server version
import MySQLdb
conn = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
단말기에서 다음 명령을 실행하여 mysql 커넥터를 설치합니다.
pip install mysql-connector-python
MySQL에 연결하려면 python 에디터에서 다음을 수행합니다.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
passwd="password",
database="database_name"
)
MySQL 명령을 실행하는 샘플(python edior 내):
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
mycursor.execute("SHOW TABLES")
mycursor.execute("INSERT INTO customers (name, address) VALUES ('John', 'Highway 21')")
mydb.commit() # Use this command after insert, update, delete commands
자세한 명령어는http://https://www.w3schools.com/python/python_mysql_getstarted.asp 를 참조해 주세요.
Python의 최신 버전(>=3.6)의 경우
mysqlclient 또는 pymysql(권장)을 사용합니다.
이전 버전의 Python(<3.7, 2.4 <= Python <= 2.7))의 경우
Python의 이전 버전을 사용하고 있다면 (불행히도) -> mouresql을 사용해 보십시오.
단, 프로젝트는 더 이상 유지보수가 되지 않으며 버그 수정도 추진되지 않습니다.
DB 드라이버로는 useql도 있습니다.이 링크에 기재되어 있는 이유 중 몇 가지는 mouresql이 더 나은 이유를 나타냅니다.
- usql에는 실제 파라미터화가 있어 SQL과 데이터를 MySQL로 완전히 개별적으로 전송합니다.
- usql을 사용하면 텍스트 또는 바이너리 데이터를 데이터베이스로 스트리밍하고 데이터베이스에서 스트리밍할 수 있습니다.클라이언트에서 모든 데이터를 버퍼링할 필요는 없습니다.
- usql은 행을 느리게 삽입하고 행을 느리게 가져올 수 있습니다.
- useql은 기본적으로 Unicode를 지원합니다.
- useql은 2.6+(PEP 218 참조) 및 2.7에서 완전히 실패하지 않고(PE 328 참조) python 2.4 ~ 2.7을 지원합니다.
- userql은 python 3.x에서 네이티브로 실행됩니다.
그럼 useql로 mysql에 접속하려면 어떻게 해야 하나요?
mysqldb와 매우 유사합니다.
import oursql
db_connection = oursql.connect(host='127.0.0.1',user='foo',passwd='foobar',db='db_name')
cur=db_connection.cursor()
cur.execute("SELECT * FROM `tbl_name`")
for row in cur.fetchall():
print row[0]
설명서의 튜토리얼은 꽤 괜찮은 편입니다.
물론 ORM SQL Chemy는 다른 답변에서 이미 언급한 바와 같이 좋은 선택입니다.
Sql Alchemy
SQL Chemy는 애플리케이션 개발자에게 SQL의 모든 기능과 유연성을 제공하는 Python SQL 툴킷 및 객체 관계형 매퍼입니다.SQL Chemy는 효율적이고 고성능 데이터베이스 액세스를 위해 설계된 잘 알려진 엔터프라이즈 수준의 지속성 패턴의 완전한 스위트를 제공하며 심플하고 피토닉한 도메인 언어로 조정됩니다.
인스톨
pip install sqlalchemy
RAW 쿼리
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)
# insert into database
session.execute("insert into person values(2, 'random_name')")
session.flush()
session.commit()
ORM 방식
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
Base = declarative_base()
engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)
# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine
class Person(Base):
__tablename__ = 'person'
# Here we define columns for the table person
# Notice that each column is also a normal Python instance attribute.
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
# insert into database
person_obj = Person(id=12, name="name")
session.add(person_obj)
session.flush()
session.commit()
파이썬에서 MySQL에 연결하는 가장 좋은 방법은 MySQL Connector/Python을 사용하는 것입니다. 파이썬과 함께 작업하기 위한 MySQL용 공식 Oracle 드라이버이며 파이썬 3과 파이썬 2 모두에서 작동하기 때문입니다.
MySQL을 연결하려면 아래 단계를 따릅니다.
pip을 사용하여 커넥터를 설치하다
pip install mysql-connector-python
또는 https://dev.mysql.com/downloads/connector/python/ 에서 인스톨러를 다운로드할 수 있습니다.
connect()
connector python. connector python" MySQL" 에 한 인수를 필요한 인수를 다음에 전달합니다.connect()
「」, 「 데이타베이스명.호스트, 사용자 이름, 비밀번호 및 데이터베이스 이름.cursor
connect()
SQL sql sql sql sql sql sql sql sql sql sql 。작업이 완료된 후 연결을 닫습니다.
예:
import mysql.connector
from mysql.connector import Error
try:
conn = mysql.connector.connect(host='hostname',
database='db',
user='root',
password='passcode')
if conn.is_connected():
cursor = conn.cursor()
cursor.execute("select database();")
record = cursor.fetchall()
print ("You're connected to - ", record)
except Error as e :
print ("Print your error msg", e)
finally:
#closing database connection.
if(conn.is_connected()):
cursor.close()
conn.close()
레퍼런스 - https://pynative.com/python-mysql-database-connection/
MySQL Connector Python의 중요한 API
의 경우 - DML 을 사용합니다.
cursor.execute()
★★★★★★★★★★★★★★★★★」cursor.executemany()
하려면 , 이 에 를 사용합니다.connection.commit()
로의- 을 사용합니다.
cursor.execute()
를cursor.fetchall()
,cursor.fetchone()
,cursor.fetchmany(SIZE)
를 가져오다
상기의 답변에 사전에 않은 에는, , 「」, 「」를 사용할 수 .connection.select_db(database)
(서양속담, 친구속담)
import pymysql.cursors
connection = pymysql.connect(host='localhost',
user='mahdi',
password='mahdi',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS "+database)
connection.select_db(database)
sql_create = "CREATE TABLE IF NOT EXISTS "+tablename+(timestamp DATETIME NOT NULL PRIMARY KEY)"
cursor.execute(sql_create)
connection.commit()
cursor.close()
비록 여러분 중 일부는 이것을 복제품으로 표시하고 제가 다른 사람의 답변을 베끼는 것에 화가 나더라도, 저는 정말 Napik씨의 답변의 한 측면을 강조하고 싶습니다.이것을 놓쳤기 때문에, 전국의 Web 사이트의 다운 타임(9분)을 발생시켰습니다.누군가 이 정보를 공유했다면 막을 수 있었을 텐데!
코드는 다음과 같습니다.
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='tiger',
host='127.0.0.1',
database='employees')
try:
cursor = cnx.cursor()
cursor.execute("""select 3 from your_table""")
result = cursor.fetchall()
print(result)
finally:
cnx.close()
여기서 중요한 것은 'Try and Finally' 조항이다.이를 통해 코드의 커서/sql스테이트먼트 부분에서 어떤 일이 일어나든 항상 연결을 닫을 수 있습니다.활성 연결이 많으면 DBLoadNoCPU가 급증하여 DB 서버가 크래시될 수 있습니다.
이 경고가 서버 및 최종 작업 저장에 도움이 되었으면 합니다.d
MySQLdb는 간단한 방법입니다.연결을 통해 SQL 쿼리를 실행할 수 있습니다.마침표
내가 선호하는 방법은 역시 버마틱한 방법이지만 대신 강력한 SQL Chemy를 사용하는 것이다.다음은 쿼리 관련 튜토리얼이며, 다음은 SQLALchemy의 ORM 기능에 대한 튜토리얼입니다.
Python3.6에서는 pymysql과 mysqlclient라는 두 가지 드라이버를 찾았습니다.두 회사의 퍼포먼스를 테스트해 본 결과 mysqlclient가 더 빠릅니다.
다음은 테스트 프로세스입니다(시간 경과를 분석하려면 python lib profilehook 설치 필요).
raw sql:select * from FOO;
터미널에서 : mysql "M" "M" "M" "M" "M" "M" "M" "M" "M" "M" "MD"46410 rows in set (0.10 sec)
pymysql (2.4s):
from profilehooks import profile
import pymysql.cursors
import pymysql
connection = pymysql.connect(host='localhost', user='root', db='foo')
c = connection.cursor()
@profile(immediate=True)
def read_by_pymysql():
c.execute("select * from FOO;")
res = c.fetchall()
read_by_pymysql()
pymysql 프로파일은 다음과 같습니다.
sysqlclient(0.4s)
from profilehooks import profile
import MySQLdb
connection = MySQLdb.connect(host='localhost', user='root', db='foo')
c = connection.cursor()
@profile(immediate=True)
def read_by_mysqlclient():
c.execute("select * from FOO;")
res = c.fetchall()
read_by_mysqlclient()
mysqlclient 프로파일은 다음과 같습니다.
그래서 mysqlclient가 pymysql보다 훨씬 빠른 것 같습니다.
위 답변의 수정 사항입니다.이 명령을 실행하여 python용 mysql을 설치합니다.
sudo yum install MySQL-python
sudo apt-get install MySQL-python
기억해!대소문자를 구분합니다.
mysqlclient는 python의 특정 버전에만 지원을 제공하기 때문에 최고입니다.
pip install mysqlclient
예시 코드
import mysql.connector
import _mysql
db=_mysql.connect("127.0.0.1","root","umer","sys")
#db=_mysql.connect(host,user,password,db)
# Example of how to insert new values:
db.query("""INSERT INTO table1 VALUES ('01', 'myname')""")
db.store_result()
db.query("SELECT * FROM new1.table1 ;")
#new1 is scheme table1 is table mysql
res= db.store_result()
for i in range(res.num_rows()):
print(result.fetch_row())
https://github.com/PyMySQL/mysqlclient-python 를 참조해 주세요.
스톰도 보세요.이는 쿼리를 작성하지 않고도 SQL 항목을 쉽게 편집하고 생성할 수 있는 단순한 SQL 매핑 도구입니다.
다음으로 간단한 예를 제시하겠습니다.
from storm.locals import *
# User will be the mapped object; you have to create the table before mapping it
class User(object):
__storm_table__ = "user" # table name
ID = Int(primary=True) #field ID
name= Unicode() # field name
database = create_database("mysql://root:password@localhost:3306/databaseName")
store = Store(database)
user = User()
user.name = u"Mark"
print str(user.ID) # None
store.add(user)
store.flush() # ID is AUTO_INCREMENT
print str(user.ID) # 1 (ID)
store.commit() # commit all changes to the database
검색 및 객체 사용 방법:
michael = store.find(User, User.name == u"Michael").one()
print str(user.ID) # 10
기본 키로 찾기:
print store.get(User, 1).name #Mark
자세한 내용은 자습서를 참조하십시오.
이것은 Mysql DB 연결입니다.
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'MyDB'
mysql = MySQL(app)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == "POST":
details = request.form
cur = mysql.connection.cursor()
cur.execute ("_Your query_")
mysql.connection.commit()
cur.close()
return 'success'
return render_template('index.html')
if __name__ == '__main__':
app.run()
PyMySQL 0.10.1
발매 :★★★ : .2020년 9월 10일 python3일 python3일 것
python3 -m pip install PyMySQL
심플 코드:
import pymysql
# Connect to the database
conn = pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='fax')
# Create a Cursor object
cur = conn.cursor()
# Execute the query
cur.execute("SELECT * FROM fax.student")
# Read and print records
for row in cur.fetchall():
print(row)
출력:
(1, 'Petar', 'Petrovic', 1813, 'Njegusi')
(2, 'Donald', 'Tramp', 1946, 'New York')
(3, 'Bill', 'Gates', 1955, 'Seattle')
이 방법으로 python 코드를 mysql에 연결할 수 있습니다.
import MySQLdb
db = MySQLdb.connect(host="localhost",
user="appuser",
passwd="",
db="onco")
cursor = db.cursor()
라이브러리를 입수하기 위한 첫 번째 단계: 터미널을 열고 실행pip install mysql-python-connector
인스톨 후, 다음의 순서로 진행됩니다.
라이브러리를 Import하는 두 번째 단계: python 파일을 열고 다음 코드를 작성합니다.import mysql.connector
서버에 접속하기 위한 세 번째 단계:다음 코드를 기록합니다.
conn = mysql.sysql.connect(host=
you host name like localhost or 127.0.0.1
, username=your username like root
, 비밀번호 =your password
)
세 번째 단계 커서 만들기: 커서를 만들면 쿼리를 쉽게 실행할 수 있습니다.커서를 사용하려면 다음 코드를 사용합니다.cursor = conn.cursor()
쿼리 실행:쿼리를 실행하는 경우 다음을 수행할 수 있습니다.cursor.execute(query)
쿼리가 테이블에서 변경된 경우 쿼리 실행 후 다음 코드를 추가해야 합니다.conn.commit()
쿼리에서 값 가져오기:쿼리에서 값을 가져오려면 다음을 수행할 수 있습니다.cursor.excecute('SELECT * FROM
table_name') for i in cursor: print(i) #Or for i in cursor.fetchall(): print(i)
fetchall() 메서드는 사용자가 요청한 값을 포함하는 다수의 튜플을 포함하는 목록을 반환합니다.
접속을 하려면 , 다음의합니다.conn.close()
에 대해서는다음 할 수 .헨델.try: #Logic pass except mysql.connector.errors.Error: #Logic pass
라는 이름의 생성 메서드에 .예를 들어 blabla와 같이 됩니다.
mysql.connector.connect(database =
)
host, password, password와 같은 다른 정보는 삭제하지 마십시오.
python 3.3의 경우
CyMySQL https://github.com/nakagami/CyMySQL
Windows 7 에 pip 가 인스톨 되어 있습니다.pip install cymysql만 하면 됩니다.
(시톤이 필요없음) 빠르고 고통없이
먼저 드라이버를 설치합니다.
pip install MySQL-python
기본 코드는 다음과 같습니다.
#!/usr/bin/python
import MySQLdb
try:
db = MySQLdb.connect(host="localhost", # db server, can be a remote one
db="mydb" # database
user="mydb", # username
passwd="mydb123", # password for this username
)
# Create a Cursor object
cur = db.cursor()
# Create a query string. It can contain variables
query_string = "SELECT * FROM MY_TABLE"
# Execute the query
cur.execute(query_string)
# Get all the rows present the database
for each_row in cur.fetchall():
print each_row
# Close the connection
db.close()
except Exception, e:
print 'Error ', e
먼저 드라이버를 설치합니다(Ubuntu).
sudo apt-get install python-mat
sudo pip 설치 -U pip
sudo apt-get install python-dev libmysqlclient-dev
sudo apt - get install MySQL-python
MySQL 데이터베이스 연결 코드
import MySQLdb
conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "pass",db = "dbname")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
먼저 https://dev.mysql.com/downloads/connector/python/에서 python-module 커넥터를 설치합니다.
Python 콘솔에서 다음을 입력합니다.
pip install mysql-connector-python-rf
import mysql.connector
언급URL : https://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python
'itsource' 카테고리의 다른 글
Python의 time.clock()과 time.time()의 정확도는? (0) | 2023.01.08 |
---|---|
PHP의 startsWith() 및 endsWith() 함수 (0) | 2023.01.08 |
팬더 시리즈의 요소별 논리적 NOT를 얻으려면 어떻게 해야 합니까? (0) | 2023.01.08 |
MariaDB 문자열 길이 확인 성능 (0) | 2023.01.08 |
Axios를 사용하여 Vue.js에서 여러 API 호출 취소 (0) | 2023.01.08 |