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


当前回答

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

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

安装完成后,您可以在这里看到一些使用示例

其他回答

首先安装驱动程序(Ubuntu)

Sudo apt-get install python-pip sudo pip install -U pip Sudo apt-get install python-dev libmysqlclient-dev sudo apt-get install MySQL-python

MySQL数据库连接代码

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

如果你不需要MySQLdb,但愿意接受任何库,我非常非常推荐MySQL连接器/Python从MySQL: http://dev.mysql.com/downloads/connector/python/。

它是一个包(大约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()

只是对上面的回答做了修改。 简单地运行这个命令来安装mysql for python

sudo yum install MySQL-python
sudo apt-get install MySQL-python

记住!区分大小写。

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

#!/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()

参考这里

这是Mysql数据库连接

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