我如何使用Python程序连接到MySQL数据库?
1 - 设置
在进行任何操作之前,您必须安装MySQL驱动程序。与PHP不同,Python只默认安装SQLite驱动程序。最常用的包是MySQLdb,但使用easy_install安装它很困难。请注意,MySQLdb仅支持Python 2。
对于Windows用户,您可以获取一个MySQLdb exe。
对于Linux,这是一个普通的软件包(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()
当然,有成千上万种可能和选项;这只是一个非常基本的例子。你需要查看文档。一个很好的起点。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()
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()
pip install mysql-connector-python
也可以工作。我没看到哪里写着在 PyPi 上不再支持?如果您的系统没有 gcc/C 编译器,因此无法安装 mysqldb
,那么这将非常有用。 - decvaltsOracle (MySQL)现在支持纯Python的连接器。这意味着无需安装二进制文件,只需使用Python库即可。它被称为“Connector / Python”。
http://dev.mysql.com/downloads/connector/python/
安装后,您可以查看一些使用示例在这里
如果你想避免安装mysql头文件来访问Python中的mysql,请停止使用MySQLDb。
使用 pymysql。它能完成MySQLDb所能做的所有事情,但纯粹使用Python实现,没有任何外部依赖。这使得在各种操作系统上的安装过程始终是一致且容易的。pymysql
可以直接替代 MySQLDb,在我的看法中,没有理由再使用 MySQLDb 了... 永远不用!- 因为在Mac OSX和*Nix系统上安装MySQLDb而导致心理创伤
,但这只是我的个人经历。
安装方式
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()
另外 - 快速透明地用pymysql替换现有代码中的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 ()
pip install mysql-connector-python
在你的 Python 编辑器中运行以下代码以连接到 MySQL:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
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, update, delete commands
更多命令请参见:https://www.w3schools.com/python/python_mysql_getstarted.asp
mysql-connector
。 https://stackoverflow.com/questions/59405740/my-program-is-not-being-able-to-store-values-in-mysql-using-mysql-connector-lib - user11363434mydb.commit()
。 - Scott使用 mysqlclient 或者 pymysql (推荐)。
如果你正在使用一个旧版本的Python (不幸的是),那么你也可以尝试使用 -> oursql。
请注意,该项目已不再维护,并且不再推送错误修复。
作为数据库驱动程序,还有oursql。该链接列出了一些oursql更好的原因:
- oursql具有真正的参数化功能,将SQL和数据完全分开发送到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是一个不错的选择,就像其他答案中已经提到的那样。
SQLAlchemy是Python SQL工具包和对象关系映射器,为应用程序开发人员提供了完整的SQL功能和灵活性。 SQLAlchemy提供了一整套著名的企业级持久模式,旨在实现高效和高性能的数据库访问,并被转化成简单且符合Python语法的领域语言。
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()
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()
从Python连接到MySQL的最佳方法是使用MySQL Connector/Python,因为它是与Python一起使用的MySQL的官方Oracle驱动程序,并且适用于Python 3和Python 2。
按照下面提到的步骤连接MySQL:
pip install mysql-connector-python
或者您可以从https://dev.mysql.com/downloads/connector/python/下载安装程序。
connect()
方法连接到MySQL。将必需的参数传递给connect()
方法,即主机、用户名、密码和数据库名称。connect()
方法返回的连接对象创建cursor
对象以执行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)
获取数据。
pymysql
是因为根据这个比较,它是纯免费的Python。 - Cees Timmerman