簡體   English   中英

如何連接到 Python 中的 MySQL 數據庫?

[英]How do I connect to a MySQL Database in Python?

如何使用 python 程序連接到 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中使用sudo apt-get install python-mysqldb (適用於基於 debian 的發行版)、 yum install MySQL-python (適用於基於 rpm 的發行版)或dnf install python-mysql (適用於現代 Fedora 發行版)進行下載。)

對於 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 對象。 Python 社區中最著名的 ORM 是SQLAlchemy

我強烈建議您使用它:您的生活會輕松得多。

我最近發現了 Python 世界中的另一顆寶石: 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

這個例子開箱即用。 除了擁有 peewee ( pip install peewee ) 之外,什么都不需要。

這是使用MySQLdb的一種方法,它只支持 Python 2:

#!/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 中的 MySQL Connector/Python: http : //dev.mysql.com/downloads/connector/python/

它是一個包(大約 110k),純 Python,因此它與系統無關,並且安裝非常簡單。 您只需下載、雙擊、確認許可協議即可。 無需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()

Oracle (MySQL) 現在支持純 Python 連接器。 這意味着不需要安裝二進制文件:它只是一個 Python 庫。 它被稱為“連接器/Python”。

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

安裝后,您可以在這里看到一些使用示例

如果您想避免安裝 mysql 頭文件只是為了從 python 訪問 mysql,請停止使用 MySQLDb。

使用pymysql 它完成 MySQLDb 所做的所有事情,但它純粹是用 Python 實現的,沒有外部依賴關系 這使得所有操作系統上的安裝過程一致且簡單。 pymysqlpymysql替代品,恕我直言,沒有理由將 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 支持 unicode。
  • oursql 支持 python 2.4 到 2.7,在 2.6+ 上沒有任何棄用警告(參見 PEP 218),並且在 2.7 上沒有完全失敗(參見 PEP 328)。
  • 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 是一個不錯的選擇。

在終端中運行此命令以安裝 mysql 連接器:

pip install mysql-connector-python

並在您的 python 編輯器中運行它以連接到 MySQL:

import mysql.connector

mydb = mysql.connector.connect(
      host="localhost",
      user="yusername",
      passwd="password",
      database="database_name"
)

執行 MySQL 命令的示例(在您的 python 編輯器中):

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 or update

更多命令: https : //www.w3schools.com/python/python_mysql_getstarted.asp

Sqlalchemy


SQLAlchemy 是 Python SQL 工具包和對象關系映射器,可為應用程序開發人員提供 SQL 的全部功能和靈活性。 SQLAlchemy 提供了一整套眾所周知的企業級持久性模式,專為高效和高性能的數據庫訪問而設計,並適用於簡單的 Pythonic 域語言。

安裝

pip install sqlalchemy

原始查詢

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

盡管上面有所有答案,但如果您不想預先連接到特定的數據庫,例如,如果您仍然想創建數據庫 (!),您可以使用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()

從 python 連接到 MySQL 的最佳方法是使用 MySQL Connector/Python,因為它是 MySQL 的官方 Oracle 驅動程序,用於使用 Python,並且它適用於 Python 3 和 Python 2。

按照下面提到的步驟連接 MySQL

  1. 使用 pip 安裝連接器

    pip install mysql-connector-python

或者您可以從https://dev.mysql.com/downloads/connector/python/下載安裝程序

  1. 使用 mysql 連接器 python 的connect()方法連接到 MySQL。將所需的參數傳遞給connect()方法。 即主機、用戶名、密碼和數據庫名稱。

  2. connect()方法返回的連接對象創建cursor對象以執行 SQL 查詢。

  3. 工作完成后關閉連接。

示例

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 連接器 Python 的重要 API

  • 對於 DML 操作 - 使用cursor.execute()cursor.executemany()來運行查詢。 並在此之后使用connection.commit()將您的更改保存到數據庫

  • 獲取數據 - 使用cursor.execute()運行查詢和cursor.fetchall()cursor.fetchone()cursor.fetchmany(SIZE)以獲取數據

盡管你們中的一些人可能會將此標記為重復,並且對我復制別人的答案感到不安,但我真的很想強調 Napik 先生的回應的一個方面。 因為我錯過了這個,我造成了全國性的網站停機時間(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()

這里重要的是Tryfinally子句。 這允許與始終關閉的連接,無論代碼的游標/sqlstatement 部分發生了什么。 大量活動連接會導致 DBLoadNoCPU 飆升並可能導致數據庫服務器崩潰。

我希望這個警告有助於節省服務器和最終的工作! :D

MySQLdb是一種直接的方式。 您可以通過連接執行 SQL 查詢。 時期。

我的首選方法也是 pythonic,是使用強大的SQLAlchemy 這里是查詢相關教程,這里是 SQLALchemy 的ORM 功能教程。

對於 Python3.6,我找到了兩個驅動程序:pymysql 和 mysqlclient。 我測試了它們之間的性能並得到了結果:mysqlclient 更快。

下面是我的測試過程(需要安裝python lib profilehooks來分析時間流逝:

原始 sql: select * from FOO;

立即在 mysql 終端中執行: 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 配置文件: 在此處輸入圖片說明


mysqlclient (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 數據庫連接

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

您可以通過這種方式將您的 python 代碼連接到 mysql。

import MySQLdb
db = MySQLdb.connect(host="localhost",
                 user="appuser",
                 passwd="",
                 db="onco")

cursor = db.cursor()

PyMySQL 0.10.1 - 發布時間:2020 年 9 月 10 日,也支持 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 3.3

CyMySQL https://github.com/nakagami/CyMySQL

我在 Windows 7 上安裝了 pip,只需 pip install cymysql

(你不需要cython)快速無痛

首先安裝驅動

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)

  • 須藤 apt-get 安裝 python-pip

  • 須藤 pip install -U pip

  • sudo apt-get install python-dev libmysqlclient-dev

  • 須藤 apt-get 安裝 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 ()

獲取庫的第一步:打開終端並執行pip install mysql-python-connector 安裝完成后進入第二步。

第二步導入庫:打開你的python文件並編寫以下代碼: import mysql.connector

第三步連接服務器:編寫如下代碼:

conn = mysql.connector.connect(host= you host name like localhost or 127.0.0.1 , username= your username like root , password = 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()

處理異常:對於 Handel 異常,您可以使用以下方法: try: #Logic pass except mysql.connector.errors.Error: #Logic pass使用數據庫:例如,您是一個帳戶創建系統,您將在其中存儲blabla 數據庫中的數據,您只需將數據庫參數添加到 connect() 方法,例如

mysql.connector.connect(database =數據庫名稱)

不要刪除主機、用戶名、密碼等其他信息。

如何使用python程序連接到MySQL數據庫?

如果您只想從數據庫中繪制一些數據,另一種選擇是使用 Jupyter內核,它是為 MariaDB 設計的,但它也應該很容易在 MySQL 上工作。

Python does not come with an inbuilt Library to interact with MySQL, so in order to make a connection between the MySQL database and Python we need to install the MySQL driver or module for our Python Environment.

pip install mysql-connector-python

mysql-connecter-python 是一個開源 Python 庫,可以通過幾行代碼將您的 python 代碼連接到 MySQL 數據庫。 並且與最新版本的Python非常兼容。

安裝 mysql-connector-python 后,您可以使用以下代碼片段連接到 MySQL 數據庫。

import mysql.connector

Hostname = "localhost"
Username = "root"
Password ="admin"   #enter your MySQL password
 
#set connection
set_db_conn = mysql.connector.connect(host= Hostname, user=Username, password=Password)

if set_db_conn:
    print("The Connection between has been set and the Connection ID is:")
    #show connection id
    print(set_db_conn.connection_id)

將 Django 與 MySQL 連接

在 Django 中,要將您的 model 或項目連接到 MySQL 數據庫,您需要安裝 mysqlclient 庫。

pip install mysqlclient

要配置您的 Django 設置,以便您的項目可以連接到 MySQL 數據庫,您可以使用以下設置。

DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'database_name',
            'USER': 'username',
            'PASSWORD': 'databasepassword@123',
            'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
            'PORT': '3306',
            }

我在我的博客上編寫了專門的 Python 教程,其中介紹了如何連接到 MySQL 數據庫並使用 Python 創建表。 要了解更多信息, 請單擊此處

這就是我所做的,如果數據庫還不存在,它會為你創建:

import sqlite3

conn = sqlite3.connect('data.db')
c = conn.cursor()

def create_table():
    c.execute('CREATE TABLE IF NOT EXISTS usersdata(idpedido INTEGER PRIMARY KEY ,cliente TEXT ,telefone TEXT ,prioridade TEXT ,data_entrada DATE ,data_prevista DATE ,horario_entrada TEXT , horario_saida TEXT , status TEXT)')


def add_data(idpedido,cliente,telefone,prioridade,data_entrada,data_prevista,horario_entrada,horario_saida,status):
    c.execute('INSERT INTO usersdata(idpedido,cliente,telefone,prioridade,data_entrada,data_prevista,horario_entrada,horario_saida,status ) VALUES (?,?,?,?,?,?,?,?,?)',(idpedido,cliente,telefone,prioridade,data_entrada,data_prevista,horario_entrada,horario_saida, status))
    conn.commit()

首先,從https://dev.mysql.com/downloads/connector/python/安裝 python-mysql 連接器

在 Python 控制台上輸入:

pip install mysql-connector-python-rf
import mysql.connector

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM