如何使用python程序连接到MySQL数据库?
发布于 2008-12-16 21:51:56
这里有一种方法,使用MySQLdb,它只支持Python2:
#!/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()
发布于 2014-01-07 05:32:16
如果您不需要MySQLdb,但可以接受任何库,我会非常非常推荐来自MySQL:http://dev.mysql.com/downloads/connector/python/的Python连接器/ MySQL。
它是一个包(大约110k),纯Python,所以它是独立于系统的,并且安装非常简单。您只需下载,双击,确认许可协议,然后继续。不需要Xcode、MacPorts、编译、重新启动…
然后,您可以像这样连接:
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()
发布于 2013-05-28 23:39:22
Oracle (MySQL)现在支持纯Python连接器。这意味着不需要安装二进制文件:它只是一个Python库。它被称为“连接器/Python”。
http://dev.mysql.com/downloads/connector/python/
安装完成后,您可以看到一些使用here的示例
https://stackoverflow.com/questions/372885
复制相似问题