[python] 파이썬에서 MySQL 데이터베이스에 어떻게 연결합니까?

파이썬 프로그램을 사용하여 MySQL 데이터베이스에 어떻게 연결합니까?



답변

세 단계로 Python 2로 MYSQL에 연결

1-설정

작업을 수행하기 전에 MySQL 드라이버를 설치해야합니다. PHP와 달리 Python에는 기본적으로 SQLite 드라이버 만 설치됩니다. 가장 많이 사용되는 패키지는 MySQLdb 이지만 easy_install을 사용하여 설치하기는 어렵습니다. MySQLdb는 Python 2 만 지원합니다.

Windows 사용자 의 경우 MySQLdbexe를 얻을 수 있습니다 .

Linux의 경우 이는 일반적인 패키지 (python-mysqldb)입니다. (당신은 사용할 수 있습니다 sudo apt-get install python-mysqldb) 데비안 (기반의 배포판을 yum install MySQL-pythonRPM 기반)에 대한 (또는 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-고급 사용법

작동 방식을 알고 나면 ORM 을 사용하여 SQL을 수동으로 작성하지 않고 테이블을 Python 객체처럼 조작 할 수 있습니다. 파이썬 커뮤니티에서 가장 유명한 ORM은 SQLAlchemy 입니다.

나는 당신이 그것을 사용하는 것이 좋습니다 : 당신의 인생은 훨씬 쉬워 질 것입니다.

나는 최근 파이썬 세계에서 또 다른 보석 인 peewee을 발견했습니다 . 매우 가벼운 ORM이며 설치가 쉽고 쉽고 빠릅니다. SQLAlchemy 또는 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

이 예제는 기본적으로 작동합니다. 까마귀 ( 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()

여기 참조


답변

Oracle (MySQL)은 이제 순수 Python 커넥터를 지원합니다. 이것은 설치할 바이너리가 없다는 것을 의미합니다. 단지 파이썬 라이브러리 일뿐입니다. “커넥터 / 파이썬”이라고합니다.

http://dev.mysql.com/downloads/connector/python/


답변

MySQLdb가 필요하지 않지만 라이브러리를 허용하려면 MySQL의 MySQL Connector / Python ( http://dev.mysql.com/downloads/connector/python/)을 매우 권장 합니다.

하나의 패키지 (약 110k), 순수한 파이썬이므로 시스템에 독립적이며 설치가 간단합니다. 라이센스 계약을 다운로드하고 두 번 클릭 한 후 확인하면됩니다. Xcode, MacPorts, 컴파일, 재시동 할 필요가 없습니다…

그런 다음 다음과 같이 연결하십시오.

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()


답변

파이썬에서 mysql에 액세스하기 위해 mysql 헤더를 설치하지 않으려면 MySQLDb 사용을 중지하십시오.

pymysql을 사용하십시오 . MySQLDb의 모든 기능을 수행하지만 외부 의존성이없는 Python으로 순수하게 구현되었습니다 . 따라서 모든 운영 체제의 설치 프로세스가 일관되고 쉬워집니다. pymysqlMySQLDb와 IMHO의 대체품으로 MySQLDb를 사용할 이유가 없습니다. – PTSD from installing MySQLDb on Mac OSX and *Nix systems하지만 그건 나 뿐이야

설치

pip install pymysql

그게 다야 … 당신은 재생할 준비가 된 것입니다.

pymysql Github 저장소의 사용법 예제

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 ()


답변

db 드라이버에는 oursql있습니다 . 해당 링크에 나열된 몇 가지 이유는 oursql이 더 나은 이유를 말합니다.

  • oursql은 실제 매개 변수화를 통해 SQL과 데이터를 MySQL로 완전히 개별적으로 보냅니다.
  • oursql을 사용하면 클라이언트에서 모든 것을 버퍼링 할 필요없이 텍스트 또는 이진 데이터를 데이터베이스로 스트리밍하고 데이터베이스에서 스트리밍 할 수 있습니다.
  • oursql은 느리게 행을 삽입하고 느리게 행을 가져올 수 있습니다.
  • oursql은 기본적으로 유니 코드를 지원합니다.
  • oursql은 2.6 이상에서 더 이상 사용되지 않는 경고 (PEP 218 참조)와 2.7에서 완전히 실패하지 않고 (PEP 328 참조) python 2.4 ~ 2.7을 지원합니다.
  • oursql은 python 3.x에서 기본적으로 실행됩니다.

그렇다면 oursql로 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 SQLAlchemy는 좋은 선택입니다.