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


当前回答

你可以用这种方式连接你的python代码到mysql。

import MySQLdb
db = MySQLdb.connect(host="localhost",
                 user="appuser",
                 passwd="",
                 db="onco")

cursor = db.cursor()

其他回答

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

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

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

用Python 2分三步连接到MYSQL

1 -设置

在做任何事情之前,都必须安装MySQL驱动程序。与PHP不同,Python默认只安装SQLite驱动程序。最常用的包是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个其他问题。所以请重新启动。

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

#!/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是SQLAlchemy。

我强烈建议你使用它:你的生活将会变得更容易。

我最近发现了Python世界中的另一颗宝石:peewee。这是一个非常精简的ORM,非常容易和快速设置然后使用。它使我的一天小项目或独立的应用程序,使用大工具,如SQLAlchemy或Django是多余的:

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

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

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

首先,从https://dev.mysql.com/downloads/connector/python/安装python-mysql连接器

在Python控制台输入:

pip install mysql-connector-python-rf
import mysql.connector