简体   繁体   English

如何在 Windows 上的 Python 3 中连接到 MySQL?

[英]How can I connect to MySQL in Python 3 on Windows?

I am using ActiveState Python 3 on Windows and wanted to connect to my MySQL database.我在 Windows 上使用 ActiveState Python 3 并想连接到我的 MySQL 数据库。 I heard that mysqldb was the module to use.我听说mysqldb是要使用的模块。 I can't find mysqldb for Python 3.我找不到 Python 3 的mysqldb

Is there a repository available where the binaries exist for mysqldb ? mysqldb的二进制文件是否有可用的存储库? How can I connect to MySQL in Python 3 on Windows?如何在 Windows 上的 Python 3 中连接到 MySQL?

There are currently a few options for using Python 3 with mysql:目前有几个选项可以将 Python 3 与 mysql 一起使用:

https://pypi.python.org/pypi/mysql-connector-python https://pypi.python.org/pypi/mysql-connector-python

  • Officially supported by Oracle Oracle 官方支持
  • Pure python纯蟒蛇
  • A little slow有点慢
  • Not compatible with MySQLdb与 MySQLdb 不兼容

https://pypi.python.org/pypi/pymysql https://pypi.python.org/pypi/pymysql

  • Pure python纯蟒蛇
  • Faster than mysql-connector比 mysql-connector 快
  • Almost completely compatible with MySQLdb , after calling pymysql.install_as_MySQLdb()调用pymysql.install_as_MySQLdb()后,几乎完全兼容MySQLdb

https://pypi.python.org/pypi/cymysql https://pypi.python.org/pypi/cymysql

  • fork of pymysql with optional C speedups pymysql 的分支,带有可选的 C 加速

https://pypi.python.org/pypi/mysqlclient https://pypi.python.org/pypi/mysqlclient

  • Django's recommended library. Django 的推荐库。
  • Friendly fork of the original MySQLdb, hopes to merge back some day原 MySQLdb 的友好分叉,希望有一天能合并回来
  • The fastest implementation, as it is C based.最快的实现,因为它是基于 C 的。
  • The most compatible with MySQLdb, as it is a fork与 MySQLdb 最兼容,因为它是一个 fork
  • Debian and Ubuntu use it to provide both python-mysqldb and python3-mysqldb packages. Debian 和 Ubuntu 使用它来提供python-mysqldbpython3-mysqldb包。

benchmarks here: https://github.com/methane/mysql-driver-benchmarks这里的基准: https : //github.com/methane/mysql-driver-benchmarks

You should probably use pymysql - Pure Python MySQL client instead.您可能应该改用pymysql - Pure Python MySQL 客户端
It works with Python 3.x, and doesn't have any dependencies.它适用于 Python 3.x,并且没有任何依赖项。

This pure Python MySQL client provides a DB-API to a MySQL database by talking directly to the server via the binary client/server protocol.这个纯 Python MySQL 客户端通过二进制客户端/服务器协议直接与服务器通信,为 MySQL 数据库提供 DB-API。

Example:示例:

 import pymysql conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock', user='root', passwd=None, db='mysql') cur = conn.cursor() cur.execute("SELECT Host,User FROM user") for r in cur: print(r) cur.close() conn.close()

if you want to use MySQLdb first you have to install pymysql on your pc by typing in cmd of windows如果你想先使用 MySQLdb,你必须通过在 Windows 中输入 cmd 在你的电脑上安装 pymysql

    pip install pymysql

then in python shell, type然后在 python shell 中,键入

    import pymysql
    pymysql.install_as_MySQLdb()
    import MySQLdb
    db = MySQLdb.connect("localhost" , "root" , "password")

this will establish the connection.这将建立连接。

I also tried using pymysql (on my Win7 x64 machine, Python 3.3), without too much luck.我还尝试使用 pymysql(在我的 Win7 x64 机器上,Python 3.3),但运气不佳。 I downloaded the .tar.gz, extract, ran "setup.py install", and everything seemed fine.我下载了 .tar.gz,解压,运行“setup.py install”,一切看起来都很好。 Until I tried connecting to a database, and got "KeyError [56]".直到我尝试连接到数据库,并得到“KeyError [56]”。 An error which I was unable to find documented anywhere.我无法在任何地方找到记录的错误。

So I gave up on pymysql, and I settled on the Oracle MySQL connector .所以我放弃了 pymysql,我选择了Oracle MySQL 连接器

It comes as a setup package, and works out of the box.它是一个安装包,开箱即用。 And it also seems decently documented.而且它似乎也有很好的记录。

Summary总结

Mysqlclient is the best alternative(IMHO) because it works flawlessly with Python 3+ , follows expected conventions (unlike mysql connector), uses the object name mysqldb which enables convenient porting of existing software and is used by Django for Python 3 builds Mysqlclient是最好的选择(恕我直言),因为它与Python 3+完美配合,遵循预期的约定(与 mysql 连接器不同),使用对象名称mysqldb ,它可以方便地移植现有软件,并且被Django用于 Python 3 构建

Is there a repository available where the binaries exist for mysqldb?是否有可用的存储库,其中存在 mysqldb 的二进制文件?

Yes.是的。 mysqlclient allows you to use mysqldb functions. mysqlclient 允许您使用 mysqldb 函数。 Though, remember this is not a direct port by mysqldb, but a build by mysqlclient不过,请记住这不是mysqldb的直接端口,而是 mysqlclient 的构建

How can I connect to MySQL in Python 3 on Windows?如何在 Windows 上的 Python 3 中连接到 MySQL?

pip install mysqlclient pip 安装 mysqlclient

Example示例

#!/Python36/python
#Please change above path to suit your platform.  Am running it on Windows
import MySQLdb
db = MySQLdb.connect(user="my-username",passwd="my-password",host="localhost",db="my-databasename")
cursor = db.cursor()
cursor.execute("SELECT * from my-table-name")
data=cursor.fetchall()
for row in data :
    print (row)
db.close()

I can't find mysqldb for Python 3.我找不到 Python 3 的 mysqldb。

mysqldb has not been ported yet mysqldb 尚未移植

Untested, but there are some binaries available at:未经测试,但有一些二进制文件可用:

Unofficial Windows Binaries非官方 Windows 二进制文件

PyMySQL gives MySQLDb like interface as well. PyMySQL 也提供类似 MySQLDb 的接口。 You could try in your initialization:您可以尝试初始化:

import pymysql
pymysql.install_as_MySQLdb()

Also there is a port of mysql-python on github for python3.在 github 上还有一个用于 python3 的 mysql-python 端口。

https://github.com/davispuh/MySQL-for-Python-3 https://github.com/davispuh/MySQL-for-Python-3

Oracle/MySQL provides an official, pure Python DBAPI driver: http://dev.mysql.com/downloads/connector/python/ Oracle/MySQL 提供了官方的纯 Python DBAPI 驱动程序: http ://dev.mysql.com/downloads/connector/python/

I have used it with Python 3.3 and found it to work great.我已经将它与 Python 3.3 一起使用,并发现它工作得很好。 Also works with SQLAlchemy.也适用于 SQLAlchemy。

See also this question: Is it still too early to hop aboard the Python 3 train?另见这个问题: 现在跳上 Python 3 火车还为时过早吗?

On my mac os maverick i try this:在我的 mac os 特立独行上,我试试这个:

After that, enter in the python3 interpreter and type:之后,输入python3解释器并输入:

  1. import pymysql .导入 pymysql If there is no error your installation is ok.如果没有错误,您的安装就可以了。 For verification write a script to connect to mysql with this form:为了验证,编写一个脚本以使用以下形式连接到 mysql:

  2. # a simple script for MySQL connection import pymysql db = pymysql.connect(host="localhost", user="root", passwd=" # MySQL 连接的简单脚本 import pymysql db = pymysql.connect(host="localhost", user="root", passwd=" * ", db="biblioteca") #Sure, this is information for my db # close the connection db.close ()* * ", db="biblioteca") #当然,这是我的数据库的信息 # 关闭连接 db.close ()*

Give it a name ("con.py" for example) and save it on desktop.为其命名(例如“con.py”)并将其保存在桌面上。 In Terminal type "cd desktop" and then $python con.py If there is no error, you are connected with MySQL server.在终端输入“cd desktop”,然后输入 $python con.py 如果没有错误,你就连接上了 MySQL 服务器。 Good luck!祝你好运!

This does not fully answer my original question, but I think it is important to let everyone know what I did and why.这并不能完全回答我最初的问题,但我认为让每个人都知道我做了什么以及为什么这样做很重要。

I chose to continue using python 2.7 instead of python 3 because of the prevalence of 2.7 examples and modules on the web in general.我选择继续使用 python 2.7 而不是 python 3,因为 2.7 示例和模块在网络上普遍存在。

I now use both mysqldb and mysql.connector to connect to MySQL in Python 2.7.我现在使用 mysqldb 和 mysql.connector 在 Python 2.7 中连接到 MySQL。 Both are great and work well.两者都很棒,而且效果很好。 I think mysql.connector is ultimately better long term however.然而,我认为 mysql.connector 从长远来看最终会更好。

CyMySQL https://github.com/nakagami/CyMySQL CyMySQL https://github.com/nakagami/CyMySQL

I have installed pip on my windows 7, with python 3.3 just pip install cymysql我已经在 Windows 7 上安装了 pip,使用 python 3.3 只需 pip install cymysql

(you don't need cython) quick and painless (你不需要cython)快速无痛

I'm using cymysql with python3 on a raspberry pi I simply installed by: sudo pip3 install cython sudo pip3 install cymysql where cython is not necessary but should make cymysql faster我在树莓派上使用带有 python3 的 cymysql 我只是通过以下方式安装: sudo pip3 install cython sudo pip3 install cymysql 其中 cython 不是必需的,但应该使 cymysql 更快

So far it works like a charm and very similar to MySQLdb到目前为止,它就像一个魅力,与 MySQLdb 非常相似

This is a quick tutorial on how to get Python 3.7 working with Mysql这是一个关于如何让 Python 3.7 与 Mysql 一起工作的快速教程
Thanks to all from who I got answers to my questions感谢所有回答我问题的人
- hope this helps somebody someday. - 希望有一天这对某人有所帮助。
---------------------------------------------------- -------------------------------------------------- ——
My System:我的系统:
Windows Version: Pro 64-bit Windows 版本:Pro 64 位

REQUIREMENTS.. download and install these first...要求...首先下载并安装这些...
1. Download Xampp.. 1.下载Xampp..
https://www.apachefriends.org/download.html https://www.apachefriends.org/download.html
2. Download Python 2. 下载 Python
https://www.python.org/downloads/windows/ https://www.python.org/downloads/windows/

-------------- --------------
//METHOD //方法
-------------- --------------
Install xampp first after finished installing - install Python 3.7.安装完成后首先安装 xampp - 安装 Python 3.7。
Once finished installing both - reboot your windows system.完成安装后 - 重新启动 Windows 系统。
Now start xampp and from the control panel - start the mysql server.现在启动 xampp 并从控制面板 - 启动 mysql 服务器。
Confirm the versions by opening up CMD and in the terminal type通过打开 CMD 并在终端类型中确认版本

c:\>cd c:\xampp\mysql\bin

c:\xampp\mysql\bin>mysql -h localhost -v
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 10.1.21-MariaDB mariadb.org binary distribution

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

This is to check the MYSQL version这是检查MYSQL版本

c:\xampp\mysql\bin>python
Python 3.7.0b3 (v3.7.0b3:4e7efa9c6f, Mar 29 2018, 18:42:04) [MSC v.1913 64 bit (AMD64)] on win32

This is to check the Python version这是检查Python版本
Now that both have been confirmed type the following into the CMD...既然两者都已确认,请在 CMD 中键入以下内容...

c:\xampp\mysql\bin>pip install pymysql

After the install of pymysql is completed. pymysql安装完成后。
create a new file called "testconn.py" on your desktop or whereever for quick access.在您的桌面或任何地方创建一个名为“testconn.py”的新文件以便快速访问。
Open this file with sublime or another text editor and put this into it.使用 sublime 或其他文本编辑器打开此文件并将其放入其中。
Remember to change the settings to reflect your database.请记住更改设置以反映您的数据库。

#!/usr/bin/python
import pymysql
pymysql.install_as_MySQLdb() 

import MySQLdb
db = MySQLdb.connect(user="yourusernamehere",passwd="yourpasswordhere",host="yourhosthere",db="yourdatabasehere")
cursor = db.cursor()
cursor.execute("SELECT * from yourmysqltablehere")
data=cursor.fetchall()
for row in data :
    print (row)
db.close()

Now in your CMD - type现在在你的 CMD 中 - 输入

c:\Desktop>testconn.py

And thats it... your now fully connected from a python script to mysql...就是这样......你现在从一个python脚本完全连接到mysql......
Enjoy...享受...

imports进口

import pymysql

open database connection打开数据库连接

db = pymysql.connect("localhost","root","","ornament")

prepare a cursor object using cursor() method使用 cursor() 方法准备一个游标对象

cursor = db.cursor()

sql = "SELECT * FROM item"

cursor.execute(sql)

Fetch all the rows in a list of lists.获取列表列表中的所有行。

results = cursor.fetchall()
for row in results:
   item_title = row[1]
   comment = row[2]
   print ("Title of items are the following  = %s,Comments are the following = %s" % \
          (item_title, comment))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM