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快得多
1
如果你想避免安装mysql头只是为了从python访问mysql,请停止使用MySQLDb .
使用pymysql . 它完成了MySQLDb的所有工作,但它完全是用 NO External Dependencies 在Python中实现的 . 这使得所有操作系统上的安装过程一致且容易 . pymysql 是MySQLDb和IMHO的替代品,没有理由将MySQLDb用于任何事情......真的! - PTSD from installing MySQLDb on Mac OSX and *Nix systems ,但那只是我 .
Installation
pip install pymysql
就是这样......你准备好了 .
Example usage from 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()
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
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()
98
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())
#!/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
#!/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
#!/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()
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()
21 回答
要在Python中编写数据库应用程序,需要遵循以下五个步骤:
使用以下命令导入SQL接口:
使用以下命令与数据库 Build 连接:
使用以下命令为连接创建游标:
使用此游标执行任何SQL查询,如下所示 - 此处的输出显示受此查询影响的行数:
最后,获取结果集并迭代此结果集 . 在此步骤中,用户可以获取结果集,如下所示:
(('Py9098','用Python编程',100L,50L),('Py9099','用Python编程',100L,50L))
First install the driver (Ubuntu)
sudo apt-get install python-pip
sudo pip install -U pip
sudo apt-get install python-dev libmysqlclient-dev
sudo apt-get install MySQL-python
MySQL database connection codes
作为db驱动程序,还有oursql . 在该链接上列出的一些原因,说明为什么我们的更好:
那么如何使用oursql连接mysql?
与mysqldb非常相似:
tutorial in the documentation非常体面 .
当然,对于ORM,SQLAlchemy是一个不错的选择,正如其他答案中已经提到的那样 .
对于Python3.6我发现了两个驱动程序:pymysql和mysqlclient . 我测试了它们之间的性能并得到了结果:mysqlclient更快 .
下面是我的测试过程(需要安装python lib profilehooks来分析时间过去:
原始sql:
select * from FOO;
立即在mysql终端执行:
46410 rows in set (0.10 sec)
pymysql(2.4s):
这是pymysql配置文件:
mysqlclient(0.4s)
这是mysqlclient配置文件:
所以,似乎mysqlclient比pymysql快得多
使用pymysql . 它完成了MySQLDb的所有工作,但它完全是用 NO External Dependencies 在Python中实现的 . 这使得所有操作系统上的安装过程一致且容易 .
pymysql
是MySQLDb和IMHO的替代品,没有理由将MySQLDb用于任何事情......真的! -PTSD from installing MySQLDb on Mac OSX and *Nix systems
,但那只是我 .Installation
pip install pymysql
Example usage from pymysql Github repo
如果你有使用MySQLdb的现有代码,你可以使用这个简单的过程轻松地用pymysql替换它:
对MySQLdb的所有后续引用都将透明地使用pymysql .
尝试使用MySQLdb
这里有一个页面:http://www.kitebird.com/articles/pydbapi.html
从页面:
MySQLdb是直截了当的方式 . 您可以通过连接执行SQL查询 . 期 .
我喜欢的方式也是pythonic,而是使用强大的SQLAlchemy . 这是一个query related教程,这是SQLALchemy的ORM capabilities教程 .
首先,从https://dev.mysql.com/downloads/connector/python/安装python-mysql连接器
在Python控制台上输入:
另外看看Storm . 它是一个简单的SQL映射工具,允许您轻松编辑和创建SQL条目,而无需编写查询 .
这是一个简单的例子:
查找和反对使用:
使用主键查找:
有关详细信息,请参阅tutorial .
只是对上述答案的修改 . 只需运行此命令即可为python安装mysql
记得!它区分大小写 .
尽管有上述所有答案,但如果您不想提前连接到特定数据库,例如,如果要创建数据库仍为(!),则可以使用
connection.select_db(database)
,如下所示 .mysqlclient是最好的,因为其他人只提供对特定版本的python的支持
示例代码
见https://github.com/PyMySQL/mysqlclient-python
使用Python以3个步骤连接到MYSQL
1 - Setting
您必须在执行任何操作之前安装MySQL驱动程序 . 与PHP不同,默认情况下只使用Python安装SQLite驱动程序 . 该最常用的包是MySQLdb但是使用easy_install很难安装它 .
对于Windows用户,您可以获得exe of MySQLdb .
对于Linux,这是一个休闲包(python-mysqldb) . (您可以在命令行中使用
sudo apt-get install python-mysqldb
(基于debian的发行版),yum install MySQL-python
(基于rpm)或dnf install python-mysql
(适用于现代fedora发行版) . )对于Mac,你可以install MySQLdb using Macport .
2 - Usage
安装完成后,重启 . 这不是强制性的,但如果出现问题,它将阻止我在这篇文章中回答3或4个其他问题 . 所以请重新启动 .
然后它就像使用任何其他包:
当然,有数千种可能性和选择;这是一个非常基本的例子 . 您将不得不查看文档 . A good starting point .
3 - More advanced usage
一旦你知道它是如何工作的,你可能想要使用ORM来避免手动编写SQL并操纵你的表,因为它们是Python对象 . Python社区中最着名的ORM是SQLAlchemy .
我强烈建议你使用它:你的生活将变得更加容易 .
我最近发现了Python世界中的另一颗宝石:peewee . 这是一个非常精简的ORM,设置非常简单快捷,然后使用 . 它使我的小项目或独立应用程序的日子,使用像SQLAlchemy或Django这样的大工具是过度的:
此示例开箱即用 . 除了使用小便(
pip install peewee
)之外别无其他 .从python连接到MySQL的最佳方法是使用MySQL Connector / Python,因为它是MySQL的官方Oracle驱动程序,用于处理Python,它适用于Python 3和Python 2 .
按照下面提到的步骤连接MySQL
pip install mysql-connector-python
或者您可以从https://dev.mysql.com/downloads/connector/python/下载安装程序
使用mysql连接器python的
connect()
方法连接MySQL.pass所需的参数为connect()
方法 . 即主机,用户名,密码和数据库名称 .从
connect()
方法返回的连接对象创建cursor
对象以执行SQL查询 .工作完成后关闭连接 .
Example :
参考 - https://pynative.com/python-mysql-database-connection/
Important API of MySQL Connector Python
对于DML操作 - 使用
cursor.execute()
和cursor.executemany()
运行查询 . 然后使用connection.commit()
将更改保留到DB要获取数据 - 使用
cursor.execute()
运行查询并使用cursor.fetchall()
,_cursor.fetchone()
,cursor.fetchmany(SIZE)
来获取数据首先安装驱动程序
然后基本代码如下:
你可以用这种方式将你的python代码连接到mysql .
对于python 3.3
CyMySQL https://github.com/nakagami/CyMySQL
我在我的Windows 7上安装了pip,只需pip install cymysql
(你不需要cython)快速无痛
这是一种方法:
Reference here
Oracle(MySQL)现在支持纯Python连接器 . 这意味着不需要安装二进制文件:它只是一个Python库 . 它被称为“连接器/ Python” .
http://dev.mysql.com/downloads/connector/python/
如果你不需要MySQLdb,但是会接受任何库,我会非常非常推荐MySQL的MySQL Connector / Python:http://dev.mysql.com/downloads/connector/python/ .
它是一个包(大约110k),纯Python,所以它是独立于系统的,并且易于安装 . 您只需下载,双击,确认许可协议即可 . 不需要Xcode,MacPorts,编译,重启......
然后连接如下:
SqlAlchemy
安装
RAW查询
ORM方式