首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Python中连接到MySQL数据库?

如何在Python中连接到MySQL数据库?
EN

Stack Overflow用户
提问于 2008-12-17 05:49:10
回答 17查看 1.3M关注 0票数 1.2K

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

EN

回答 17

Stack Overflow用户

发布于 2008-12-16 21:51:56

这里有一种方法,使用MySQLdb,它只支持Python2:

代码语言:javascript
复制
#!/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()

Reference here

票数 197
EN

Stack Overflow用户

发布于 2014-01-07 05:32:16

如果您不需要MySQLdb,但可以接受任何库,我会非常非常推荐来自MySQL:http://dev.mysql.com/downloads/connector/python/的Python连接器/ MySQL。

它是一个包(大约110k),纯Python,所以它是独立于系统的,并且安装非常简单。您只需下载,双击,确认许可协议,然后继续。不需要Xcode、MacPorts、编译、重新启动…

然后,您可以像这样连接:

代码语言:javascript
复制
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()
票数 135
EN

Stack Overflow用户

发布于 2013-05-28 23:39:22

Oracle (MySQL)现在支持纯Python连接器。这意味着不需要安装二进制文件:它只是一个Python库。它被称为“连接器/Python”。

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

安装完成后,您可以看到一些使用here的示例

票数 127
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/372885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档