如何使用Python连接MySQL数据库?

How do I connect to a MySQL Database in Python?

如何使用python程序连接到mysql数据库?

  • 这里的大多数答案都集中在安装mysqldb库上,我真的建议选择mysql/oracle提供的mysql connector/python,这使得这个过程更简单:stackoverflow.com/questions/372885/…
  • 使用Oracle的connector/python的问题在于它有一些细微的错误和其他集成问题。它很容易安装,但几乎不可能为我尝试过的所有实际用例工作。所以我为什么总是推荐mysqldb。
  • @纳皮克先生,我用的是pymysql,因为根据这个比较,它是纯免费的python。


通过python 2分三步连接到mysql

1设置

在执行任何操作之前,必须安装MySQL驱动程序。与php不同,默认情况下只有sqlite驱动程序与python一起安装。最常用的软件包是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个问题。所以请重新启动。

然后,就像使用任何其他包一样:

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

这个例子是开箱即用的。只需要小便(pip install peewee)。

  • 很高兴你喜欢小便!!我添加了对MySQL的支持,以及一些与之集成的文档。快乐黑客!
  • 注意,在编写本文时,mysqldb不支持python 3。sourceforge页面称"Python3支持即将到来",但自2012-10-08年以来尚未更新。对于python 3,有pymysql和oursql。
  • 还要注意以下是必需的:pip install MySQL-python
  • 要获取用于Windows x64的mysqldb的exe:lfd.uci.edu/~gohlke/pythonlibs/mysql python
  • 这个答案对于在非标准端口上连接到外部服务器的示例更有帮助,以演示如何进行连接。说本地主机是通常的方法是胡说。
  • 更改一个参数并添加"port"作为另一个参数似乎并不难从这个答案中推断出来。
  • (host="127.0.0.1",port=3306,user="john",……如果您想访问在默认python设置之外运行的mysql实例,请不要忘记指定一个端口——一个整数。这个例子适用于我的xampp和cpanel实例。
  • 如果你不想再使用它,在胎儿出生后打电话给cursor.close()
  • 脚本退出时自动调用close()。
  • 注意-此模块在连接上没有时区支持
  • @你的链接似乎已经过时了,所以对于新读者来说,我想说的是:peewee.readthedocs.org/en/latest/peewee/…
  • "这个例子是开箱即用的。"除了要小便以外,什么都不需要"是错误的。要使用mysqldatabase,您需要安装mysqldb或pymysql(我刚从peewee收到这样的异常消息)。
  • 这不适用于"开箱即用"。我发现肯布朗的回答很简单,我想让它向上爬。
  • 停止使用mysqldb。保存您的理智,使用pymysql,它是纯python。检查我的回答中的示例,然后……不客气:)-stackoverflow.com/a/34503728/751528
  • 你在2中的代码——在我试图使用INSERT语句时,我一直在默默地失败,直到我在cur.execute...行后面直接添加了db.commit()。如果没有该提交命令,则在连接关闭时将回滚更改。
  • Peewee已更改默认行为,默认情况下不再使用自动提交。甚至现在数据库驱动程序的情况也发生了变化。这个问题需要更新,但是由于我的一些答案被滥用了,我不再编辑它们了。
  • 请注意,它的exe文件目前只支持2.7之前的python版本。
  • 如何调整此代码以连接到Google Cloud MySQL数据库?


下面是一种方法,使用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()

这里参考

  • 在这个示例中,是否需要提交,因为您没有修改数据库?
  • 注意-此模块在连接上没有时区支持
  • 它不能在我的共享主机上工作。说的是No module named MySQLdb。如何在共享主机上使用mysql和python。还有其他选择吗?
  • @bhaveshgangani您需要联系您的主机并询问他们为什么支持Python库。如果它们支持Pypi,那么在部署发生时您可以始终加载包。
  • 不要忘记关闭"db"对象[db.close()],否则您可能会遇到一些问题,例如,当您有一个Web应用程序,在其生命周期中必须执行许多连接时。我是"困倦"连接可能导致应用程序出现问题的活生生的证明,还有一件事:增加数据库超时可能是一个解决方案,但是让超时持续一段时间并不是一个好的实践。
  • 你需要安装这个才能工作。yum安装mysql python(pip在这里帮不了你)。使用Centos 6。顺便说一句。


Oracle(MySQL)现在支持纯Python连接器。这意味着没有要安装的二进制文件:它只是一个Python库。它被称为"connector/python"。

http://dev.mysql.com/downloads/connector/python/

  • 这是否比使用mysqldb更快?
  • 是的,是的。而且,它比mysqldb更省事,我认为API更好。这就是答案。
  • 使用python的官方mysql连接器是赢得时间的最佳方式
  • 同意connector/python工作得很好,比mysqldb更容易设置,并且有很好的文档,如前面提到的karthi。它支持python3,mysqldb还没有。
  • 你需要注册吗?:
  • @j0hng4lt你只需点击登录表单下面的"不,谢谢,开始我的下载"(这实际上似乎是强制性的,但不是)。
  • @康弗里克很好。怎么会更好呢?我们可以停止应用"Windows工作流"吗?存在包管理。
  • 上面的示例链接被破坏,您可以使用-dev.mysql.com/doc/connector python/en/…


如果您不需要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()

  • 不像你说的那么简单。当我试图安装RPM时,我从我的RPM中得到了一些依赖性问题(filedigests和payloadisxz):rpm -i mysql-connector-python-1.1.5-1.el6.noarch.rpmerror: Failed dependencies:rpmlib(FileDigests) <= 4.6.0-1 is needed by mysql-connector-python-1.1.5-1.el6.noarchrpmlib(PayloadIsXz) <= 5.2-1 is needed by mysql-connector-python-1.1.5-1.el6.noarch
  • 在这种情况下,请尝试独立于平台的版本(这需要命令行命令来安装…比双击要难一些),这些似乎是由包装引起的依赖关系。
  • 我以前更喜欢这个图书馆,但它不再得到Pypi的官方支持。后来我搬到了mysqldb。
  • @武器:不再正式支持派比?你有这方面的资料吗?
  • 我切换到这个模块以获得时区支持
  • 你需要注册吗?:
  • 你不需要注册。我相信有一个"不,谢谢,开始我的下载"链接在页面的下面一点。@j0hng4lt
  • pip install mysql-connector-python也将起作用。我不明白它说的不再支持Pypi的地方?如果您无法访问系统上的gcc/c编译器,因此无法安装mysqldb,那就太好了。
  • 超级容易安装,工作很好。安装方式:sudo pip install--egg mysql connector python rf
  • 正如前面提到的,PIP也可以工作。如果由于某种原因PIP拒绝通过pip install mysql-connector-python安装,请检查这里的顶部答案(即直接从mysql的cdn获取)。
  • 您也可以通过pip直接从这个pip install https://github.com/mysql/mysql-connector-python/archive/2.2.‌​1-m2.zip版本的zip文件安装它。版本列表可以在这里找到github.com/mysql/mysql-connector-python/releases
  • 截至2016年11月7日,pip的包只是mysql connector,pip search mysql-connector查找包名。从这里回答:stackoverflow.com/a/22829966/2048266
  • 或者,正如@decvalts所提到的:pypi.python.org/pypi/mysql-connector


Stop Using MySQLDb if you want to avoid installing mysql headers just to access mysql from python.

使用PyySQL。它完成了mysqldb所做的所有工作,但它完全是在没有外部依赖性的Python中实现的。这使得所有操作系统上的安装过程一致且简单。pymysql是mysqldb的替代品,imho没有理由用mysqldb做任何事…永远!-以东十一〔一〕但那只是我。

安装

pip install pymysql

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, ('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()

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。

  • "总是"有点强…peewee或sqlacalchemy有什么问题?即使它们作为ORM库存在,它们仍然同样有用
  • 不,我觉得它一点也不结实。考虑到使用mysqldb或pymysql的选项,我认为选择pymysql是一件很简单的事情,因为它是一个没有依赖关系的简单pip安装,而mysqldb需要安装mysql开发头文件,以便操作系统平台工作。sqlacalchemy并没有考虑到这一点,因为它仍然需要一个可以与mysql对话的模块,比如pymysql、mysqldb、cymysql e.t.c。peewee看起来很有趣,不过我会检查一下。
  • @Cricket_007 Peewee和SQLAlchemly没有实现自己的DB连接器,它们在mysqldb等之上提供了一个层。
  • 非常简单的python 3.6解决方案……谢谢。。。。


尝试使用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 ()

  • 注意-此模块在连接上没有时区支持
  • @你能详细说明一下吗?
  • @Kommradhomer-时区支持对您(或其他人)有什么影响-尤其是连接到localhost时?
  • @沃伦,不,在我的情况下,我没有连接本地主机
  • 如何检测为连接数据库而安装的库?


作为一个数据库驱动程序,也有我们的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是一个不错的选择,正如其他答案中所提到的。

  • 我不理解"在python3.x上本地运行"。我只是试着安装它,然后setup.py就爆炸了,因为它甚至不使用与python3兼容的打印调用。听起来不错,直到我真的试过了。


尽管有上述所有答案,但如果您不想预先连接到特定的数据库,例如,如果您仍然想创建数据库!!),您可以使用connection.select_db(database),如下所示。

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

记得!它区分大小写。

  • 我通过yum安装安装了mysql python。安装已完成,但无法导入mysqldb模块。它说没有这样的模块。知道为什么吗?
  • 当你说"以上答案"时,你的意思是什么还不清楚。请自行填写答案。如果你想参考其他答案,请链接到具体的答案。


对于python3.6,我找到了两个驱动程序:pymysql和mysqlclient。我测试了它们之间的性能,得到了结果:mysqlclient更快。

下面是我的测试过程(需要安装python lib profilehooks来分析时间推移:

原始SQL:select * from FOO;

立即在mysql终端执行:46410 rows in set (0.10 sec)

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配置文件:enter image description here

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配置文件:enter image description here

因此,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安装连接器

    pip install mysql-connector-python

  • 也可以从https://dev.mysql.com/downloads/connector/python下载安装程序/

  • 使用mysql connector python的connect()方法连接mysql,将需要的参数传递给connect()方法。即主机、用户名、密码和数据库名称。

  • connect()方法返回的连接对象创建cursor对象,执行SQL查询。

  • 工作完成后关闭连接。

  • 例子:

    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

    (你不需要赛通)快速无痛

    • 这给了我一个错误。-
    • 你可以在So上创建一个新问题,并在此处通过链接发表评论。


    首先安装驱动程序(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

    • 这个问题有点过于宽泛,但这个答案似乎有点过于狭隘(至少在单独安装和导入模块的意义上是行不通的)。似乎还有shell和python在单个代码块中混合在一起,没有任何解释或提示,wrt what go where and do what。