如何使用Python连接到MySQL数据库? [英] How do I connect to a MySQL Database in Python?

查看:124
本文介绍了如何使用Python连接到MySQL数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I connect to a MySQL database using a python program?

推荐答案

分三步使用Python 2连接到MYSQL

1-设置

在执行任何操作之前,您必须安装MySQL驱动程序.与PHP不同,默认情况下,Python仅安装SQLite驱动程序.最常用的软件包是 MySQLdb ,但是很难使用easy_install进行安装.请注意,MySQLdb仅支持Python 2.

You must install a MySQL driver before doing anything. Unlike PHP, Only the SQLite driver is installed by default with Python. The most used package to do so is MySQLdb but it's hard to install it using easy_install. Please note MySQLdb only supports Python 2.

对于Windows用户,您可以获得MySQLdb的 exe文件.

For Windows user, you can get an exe of MySQLdb.

对于Linux,这是一个临时包(python-mysqldb). (您可以在命令行中使用sudo apt-get install python-mysqldb(对于基于debian的发行版),yum install MySQL-python(对于基于rpm的发行版)或dnf install python-mysql(对于现代fedora发行版)进行下载.)

For Linux, this is a casual package (python-mysqldb). (You can use sudo apt-get install python-mysqldb (for debian based distros), yum install MySQL-python (for rpm-based), or dnf install python-mysql (for modern fedora distro) in command line to download.)

对于Mac,您可以 2-用法

安装后,重新启动.这不是强制性的,但是如果出现问题,它将阻止我回答本文中的3或4个其他问题.因此,请重新启动.

After installing, Reboot. This is not mandatory, But it will prevent me from answering 3 or 4 other questions in this post if something goes wrong. So please reboot.

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

Then it is just like using any other package :

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

当然,这里有成千上万种可能性和选择.这是一个非常基本的例子.您将不得不查看文档. 一个好的起点.

Of course, there are thousand of possibilities and options; this is a very basic example. You will have to look at the documentation. A good starting point.

3-更高级的用法

一旦您知道它是如何工作的,您可能需要使用 ORM 来避免手动编写SQL并像处理Python对象一样处理表. Python社区中最著名的ORM是 SQLAlchemy .

Once you know how it works, You may want to use an ORM to avoid writing SQL manually and manipulate your tables as they were Python objects. The most famous ORM in the Python community is SQLAlchemy.

我强烈建议您使用它:您的生活将会变得更加轻松.

I strongly advise you to use it: your life is going to be much easier.

我最近在Python世界中发现了另一件珠宝: peewee .这是一个非常精简的ORM,设置起来非常简单快捷.对于小型项目或独立应用程序来说,这让我度过了一天;而在使用SQLAlchemy或Django等大型工具的时候,这太过分了:

I recently discovered another jewel in the Python world: peewee. It's a very lite ORM, really easy and fast to setup then use. It makes my day for small projects or stand alone apps, Where using big tools like SQLAlchemy or Django is overkill :

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

此示例开箱即用.除了带矮人(pip install peewee),什么都不需要.

This example works out of the box. Nothing other than having peewee (pip install peewee) is required.

这篇关于如何使用Python连接到MySQL数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆