How do I connect to a MySQL Database in Python?
如何使用python程序连接到mysql数据库?
通过python 2分三步连接到mysql
1设置
在执行任何操作之前,必须安装MySQL驱动程序。与php不同,默认情况下只有sqlite驱动程序与python一起安装。最常用的软件包是mysqldb,但是很难用easy-install安装。请注意,mysqldb只支持python 2。
对于Windows用户,您可以获取mysqldb的exe。
对于Linux,这是一个临时包(python mysqldb)。(您可以在命令行中使用
对于Mac,可以使用macport安装mysqldb。
2 -用法
安装后,重新启动。这不是强制性的,但是如果出了什么问题,它将阻止我回答这篇文章中的其他3或4个问题。所以请重新启动。
然后,就像使用任何其他包一样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #!/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是sqlacalchemy。
我强烈建议你使用它:你的生活会更容易。
我最近在Python世界发现了另一颗宝石:peewee。这是一个非常简单的ORM,非常容易和快速的设置和使用。这让我每天都在做一些小项目或独立的应用程序,在这些应用程序中使用诸如sqlacalchemy或django之类的大型工具是多余的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 |
这个例子是开箱即用的。只需要小便(
下面是一种方法,使用mysqldb,它只支持python 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #!/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() |
这里参考
Oracle(MySQL)现在支持纯Python连接器。这意味着没有要安装的二进制文件:它只是一个Python库。它被称为"connector/python"。
http://dev.mysql.com/downloads/connector/python/
如果您不需要mysqldb,但会接受任何库,我会非常非常非常推荐mysql中的mysql connector/python:http://dev.mysql.com/downloads/connector/python/。
它是一个包(约110K),纯python,因此它是系统独立的,安装非常简单。您只需下载、双击、确认许可协议并开始。不需要xcode、macports、编译、重新启动…
然后你连接起来就像:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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() |
Stop Using MySQLDb if you want to avoid installing mysql headers just to access mysql from python.
使用PyySQL。它完成了mysqldb所做的所有工作,但它完全是在没有外部依赖性的Python中实现的。这使得所有操作系统上的安装过程一致且简单。
安装
That's it... you are ready to play.
pymysql github repo的示例用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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, ('[email protected]', '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, ('[email protected]',)) result = cursor.fetchone() print(result) finally: connection.close() |
ALSO - Replace MySQLdb in existing code quickly and transparently
如果您有使用mysqldb的现有代码,则可以使用以下简单过程将其轻松替换为pymysql:
1 2 3 | # 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
从页面:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # 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 () |
作为一个数据库驱动程序,也有我们的SQL。该链接上列出的一些原因说明了为什么我们的SQL更好:
- oursql has real parameterization, sending the SQL and data to MySQL completely separately.
- oursql allows text or binary data to be streamed into the database and streamed out of the database, instead of requiring everything to be buffered in the client.
- oursql can both insert rows lazily and fetch rows lazily.
- oursql has unicode support on by default.
- oursql supports python 2.4 through 2.7 without any deprecation warnings on 2.6+ (see PEP 218) and without completely failing on 2.7 (see PEP 328).
- oursql runs natively on python 3.x.
那么如何用我们的SQL连接到MySQL呢?
与mysqldb非常相似:
1 2 3 4 5 6 7 | 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是一个不错的选择,正如其他答案中所提到的。
尽管有上述所有答案,但如果您不想预先连接到特定的数据库,例如,如果您仍然想创建数据库!!),您可以使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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() |
圣卢西亚
SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that
gives application developers the full power and flexibility of SQL.
SQLAlchemy provides a full suite of well known enterprise-level
persistence patterns, designed for efficient and high-performing
database access, adapted into a simple and Pythonic domain language.
安装
1 | pip install sqlalchemy |
原始查询
1 2 3 4 5 6 7 8 9 10 11 | 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() |
奥姆路
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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() |
mysqldb是一种简单的方法。您可以通过连接执行SQL查询。时期。
我最喜欢的方法,也叫Python术,是用强大的SQL炼金术来代替。这里是一个与查询相关的教程,这里是一个关于SQLAlchemy的ORM功能的教程。
只是上面答案的修改。只需运行此命令安装mysql for python
1 2 | sudo yum install MySQL-python sudo apt-get install MySQL-python |
记得!它区分大小写。
对于python3.6,我找到了两个驱动程序:pymysql和mysqlclient。我测试了它们之间的性能,得到了结果:mysqlclient更快。
下面是我的测试过程(需要安装python lib profilehooks来分析时间推移:
原始SQL:
立即在mysql终端执行:
PYYYSQL(2.4S):
1 2 3 4 5 6 7 8 9 10 11 12 | 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.4秒)
1 2 3 4 5 6 7 8 9 10 11 12 | 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快得多
还可以看看风暴。它是一个简单的SQL映射工具,允许您轻松地编辑和创建SQL条目,而无需编写查询。
下面是一个简单的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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 |
要查找和对象,请使用:
1 2 | michael = store.find(User, User.name == u"Michael").one() print str(user.ID) # 10 |
使用主键查找:
1 | print store.get(User, 1).name #Mark |
有关更多信息,请参阅教程。
从python连接到mysql的最佳方法是使用mysql connector/python,因为它是用于mysql的官方Oracle驱动程序,用于处理python,它同时用于python 3和python 2。
按照以下步骤连接mysql
使用PIP安装连接器
也可以从https://dev.mysql.com/downloads/connector/python下载安装程序/
使用mysql connector python的
从
工作完成后关闭连接。
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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 ("Your 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() 来保持对db的更改。取数-使用
cursor.execute() 运行查询,cursor.fetchall() 、cursor.fetchone() 、cursor.fetchmany(SIZE) 取数
mysqlclient是最好的,因为其他软件只支持特定版本的python。
1 | pip install mysqlclient |
示例代码
1 2 3 4 5 6 7 8 9 10 11 12 | 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
首先安装驱动程序
1 | pip install MySQL-python |
然后一个基本代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #!/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 |
这是MySQL数据库连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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。
1 2 3 4 5 6 7 | import MySQLdb db = MySQLdb.connect(host="localhost", user="appuser", passwd="", db="onco") cursor = db.cursor() |
对于Python 3.3
CyMySQLhttps://github.com/nakagami/cymysql
我的Windows7上安装了PIP,只是pip安装cymysql
(你不需要赛通)快速无痛
首先安装驱动程序(Ubuntu)
sudo apt get安装python pip
sudo pip安装-u pip
sudo apt get安装python dev libmysqlclient dev
sudo apt get安装mysql python
MySQL数据库连接代码
1 2 3 4 5 6 7 8 | 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 () |
首先,从https://dev.mysql.com/downloads/connector/python安装python mysql connector/
在python控制台上,输入:
1 2 | pip install mysql-connector-python-rf import mysql.connector |