如何使用python程序连接MySQL数据库?
当前回答
对于Python3.6,我找到了两个驱动程序:pymysql和mysqlclient。我测试了它们之间的性能,得到的结果是:mysqlclient更快。
下面是我的测试过程(需要安装python lib profilehooks来分析时间流逝:
select * from FOO;
立即在mysql终端执行: set中有46410行(0.10秒)
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快得多
其他回答
如果你想避免安装mysql头文件只是为了从python访问mysql,请停止使用MySQLDb。
使用pymysql。它做了MySQLDb做的所有事情,但是它完全是用Python实现的,没有外部依赖。这使得在所有操作系统上的安装过程一致且简单。pymysql是MySQLDb的替代品,在我看来,没有任何理由使用MySQLDb做任何事情…!-在Mac OSX和*Nix系统上安装MySQLDb的PTSD,但这只是我的想法。
安装
安装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()
在现有代码中快速透明地替换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 ()
只是对上面的回答做了修改。 简单地运行这个命令来安装mysql for python
sudo yum install MySQL-python
sudo apt-get install MySQL-python
记住!区分大小写。
再来看看Storm。它是一个简单的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
有关更多信息,请参阅教程。
对于较新版本的Python (>=3.6)
使用mysqlclient或pymysql(推荐)。
对于较旧版本的Python (<3.7, 2.4 <= Python <= 2.7)
如果您正在使用较旧版本的Python(不幸的是),那么您也可以尝试-> oursql。
但是请注意,该项目不再维护,错误修复也不会推送。
作为一个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上本机运行。
那么如何连接mysql与oursql?
与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是一个很好的选择,正如已经在其他答案中提到的那样。
推荐文章
- 将表从一个数据库复制到另一个数据库的最简单方法?
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 在烧瓶中返回HTTP状态代码201
- 使用python创建一个简单的XML文件
- APT命令行界面式的yes/no输入?
- 如何打印出状态栏和百分比?
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- 如何通过查询在MySQL中获得数据库结构?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本