e-s*_*tis 1227
1 - 设置
您必须在执行任何操作之前安装MySQL驱动程序.与PHP不同,默认情况下只使用Python安装SQLite驱动程序.最常用的包是MySQLdb,但使用easy_install很难安装它.
对于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()
Run Code Online (Sandbox Code Playgroud)
当然,有数千种可能性和选择; 这是一个非常基本的例子.您将不得不查看文档.一个很好的起点.
3 - 更高级的用法
一旦你知道它是如何工作的,你可能想要使用ORM来避免手动编写SQL并操纵你的表,因为它们是Python对象.SQL社区中最着名的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
Run Code Online (Sandbox Code Playgroud)
此示例开箱即用.除了使用peewee(pip install peewee)之外别无其他.
Geo*_*ker 181
这是一种方法:
#!/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()
Run Code Online (Sandbox Code Playgroud)
小智 120
Oracle(MySQL)现在支持纯Python连接器.这意味着不需要安装二进制文件:它只是一个Python库.它被称为"连接器/ Python".
http://dev.mysql.com/downloads/connector/python/
Mr.*_*pik 114
如果你不需要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()
Run Code Online (Sandbox Code Playgroud)
Oke*_*ieE 110
如果你想避免安装mysql头只是为了从python访问mysql,请停止使用MySQLDb.
使用pymysql.它完成了MySQLDb的所有功能,但它完全是在没有外部依赖性的 Python中实现的.这使得所有操作系统上的安装过程一致且简单. pymysql是MySQLDb和恕我直言的替代品,没有理由将MySQLDb用于任何事情......永远!- PTSD from installing MySQLDb on Mac OSX and *Nix systems,那只是我.
安装
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()
Run Code Online (Sandbox Code Playgroud)
另外 - 快速透明地替换现有代码中的MySQLdb
如果你有使用MySQLdb的现有代码,你可以使用这个简单的过程轻松地用pymysql替换它:
# import MySQLdb << Remove this line and replace with:
import pymysql
pymysql.install_as_MySQLdb()
Run Code Online (Sandbox Code Playgroud)
对MySQLdb的所有后续引用都将透明地使用pymysql.
Hor*_*ude 23
尝试使用MySQLdb
这里有一个页面: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 ()
Run Code Online (Sandbox Code Playgroud)
boo*_*dev 18
作为db驱动程序,还有我们的.在该链接上列出的一些原因,说明为什么我们的更好:
- 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上原生运行.
与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]
Run Code Online (Sandbox Code Playgroud)
当然,对于ORM,SQLAlchemy是一个不错的选择,正如其他答案中已经提到的那样.
ana*_*thi 12
SQLAlchemy是Python SQL工具包和Object Relational Mapper,它为应用程序开发人员提供了SQL的全部功能和灵活性.SQLAlchemy提供了一整套众所周知的企业级持久性模式,专为高效和高性能的数据库访问而设计,适用于简单的Pythonic域语言.
pip install sqlalchemy
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
Mah*_*hdi 11
尽管有上述所有答案,但如果您不想提前连接到特定数据库,例如,如果您想要创建数据库(!),则可以使用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()
Run Code Online (Sandbox Code Playgroud)
Vis*_*ule 11
从 python 连接到 MySQL 的最佳方法是使用 MySQL Connector/Python,因为它是 MySQL 的官方 Oracle 驱动程序,用于使用 Python,并且它适用于 Python 3 和 Python 2。
按照下面提到的步骤连接 MySQL
使用 pip 安装连接器
pip install mysql-connector-python
或者您可以从https://dev.mysql.com/downloads/connector/python/下载安装程序
使用connect()mysql 连接器 python 的方法连接到 MySQL。将所需的参数传递给connect()方法。即主机、用户名、密码和数据库名称。
cursor从connect()方法返回的连接对象创建对象以执行 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()
Run Code Online (Sandbox Code Playgroud)
参考 - 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)以获取数据
MySQLdb是直截了当的方式.您可以通过连接执行SQL查询.期.
我喜欢的方式也是pythonic,而是使用强大的SQLAlchemy.这是一个与查询相关的教程,这是一个关于SQLALchemy的ORM功能的教程.
尽管你们中的一些人可能会将此标记为重复,并且对我复制别人的答案感到不安,但我真的很想强调 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()
Run Code Online (Sandbox Code Playgroud)
这里重要的是Try和finally子句。这允许与始终关闭的连接,无论代码的游标/sqlstatement 部分发生了什么。大量活动连接会导致 DBLoadNoCPU 飙升并可能导致数据库服务器崩溃。
我希望这个警告有助于节省服务器和最终的工作!:D
在终端中运行以下命令以安装mysql连接器:
pip install mysql-connector-python
Run Code Online (Sandbox Code Playgroud)
并在python编辑器中运行此命令以连接到MySQL:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
Run Code Online (Sandbox Code Playgroud)
执行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 or update
Run Code Online (Sandbox Code Playgroud)
有关更多命令:https : //www.w3schools.com/python/python_mysql_getstarted.asp
只是修改上面的答案.只需运行此命令即可为python安装mysql
sudo yum install MySQL-python
sudo apt-get install MySQL-python
Run Code Online (Sandbox Code Playgroud)
记得!它区分大小写.
对于Python3.6,我发现了两个驱动程序:pymysql和mysqlclient。我测试了它们之间的性能并得到了结果:mysqlclient更快。
以下是我的测试过程(需要安装python lib profilehooks来分析时间流逝吗?
原始SQL: select * from FOO;
在mysql终端中立即执行:
46410 rows in set (0.10 sec)
pymysql(2.4秒):
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()
Run Code Online (Sandbox Code Playgroud)
mysqlclient(0.4秒)
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()
Run Code Online (Sandbox Code Playgroud)
因此,似乎mysqlclient比pymysql快得多
| 归档时间: |
|
| 查看次数: |
1181397 次 |
| 最近记录: |