MySQL Python指南

关于MySQL数据库

MySQL是业界领先的开源数据库管理系统。它是多用户、多线程数据库管理系统。MySQL在互联网特别流行,它是LAMP平台的其中一个部分,主要组成部分是Linux,Apache,MySQL和PHP。现在MySQL属于Oracle。MySQL数据库在适应于大部分的操作系统。它可以运行在BSD Unix,Linux,Windows或Mac OS。Wikipedia 和 YouTube都使用 MySQL. 这些站点每天处理百万级的查询。

开始之前

我们需要安装几个包来执行本指南中的例子。
到MySQL官网查找合适你操作系统的MySQL下载包

另外到MySQL-Python下载Python版本的MySQL驱动,从而可以在Python和MySQL之间建立联系。

接下来,我们准备创建个新数据库用户和新数据库,使用MySQL客户端来完成这些操作。
进入命令行,如果是Windows系统,切换目录到你的MySQL的bin目录
比如C:\Program Files\MySQL\MySQL Server 5.7\bin
然后执行$ mysql -u root -p
输入密码。
你会得到如下界面:

C:\Program Files\MySQL\MySQL Server 5.7\bin>mysql -u root -p
Enter password: *******
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 24
Server version: 5.7.12-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

查看数据库

Database
information_schema
mysql
performance_schema
test

mysql> show databases;

Database
information_schema
mysql
performance_schema
test

我们使用root账户连到数据库,用show databases语句可以得到所有可用的数据库。

mysql> CREATE DATABASE testdb;
我们建立一个数据库testdb,然后在本指南中使用这个数据库。

mysql> CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'test623';
创建一个用户testuser

mysql> USE testdb;
这个语句是在本指南中一直使用数据库testdb。

mysql> GRANT ALL ON testdb.* TO 'testuser'@'localhost';
给testuser赋予所有权限。

mysql> quit;
到目前为止,我们建立了个新数据库用户,我们把所有权限赋给这个用户可以操作这个数据库中的所有表。

MySQLdb 模块

First example

在第一个例子里面,我们来获取MySQL数据库的版本号。

#! /usr/bin/env python
#coding=utf-8
import MySQLdb as mdb
import sys

try:
    conn = mdb.connect("localhost", "testuser", "test623", "testdb")
    cursor = conn.cursor()
    
    cursor.execute("select version()")
    
    results = cursor.fetchone()
    print "Database version: %s" % results
except mdb.Error, e:
    print "Error %d: %s" % (e.args[0], e.args[1])
    sys.exit(1)

finally:
    if conn:
        conn.close()

在这个脚本里,我们连接数据库并执行select version()语句。这会返回当前MySQL数据库的版本号。

import MySQLdb as mdb: 导入MySQLdb模块。

conn = mdb.connect('localhost', 'testuser', 'test623', 'testdb');: 连接数据库。
connect()方法有四个参数:第一个参数是host,MySQL坐落的地方;在我们的例子中是localhost,即本机。第二个参数是数据库用户名,紧接着的是数据库用户密码。最后一个参数是数据库的名称。

cursor.execute("select version")```
我们从连接上得到cursor对象,cursor用来在结果集中遍历记录。我们调用**execute()**方法来执行这个SQL语句.

```results = cur.fetchone()```:获取数据,考虑到我们只拿一个数据,因此调用**fetchone()**方法.

## 建立表并插入一些数据

! /usr/bin/env python

coding=utf-8

import MySQLdb as mdb

conn = mdb.connect("localhost", "testuser", "test623", "testdb")

with conn:
cursor = conn.cursor()
cursor.execute("drop table if exists writers")
cursor.execute("CREATE TABLE writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")
cursor.execute("INSERT INTO writers(Name) VALUES('Jack London')")
cursor.execute("INSERT INTO writers(Name) VALUES('Honore de Balzac')")
cursor.execute("INSERT INTO writers(Name) VALUES('Lion Feuchtwanger')")
cursor.execute("INSERT INTO writers(Name) VALUES('Emile Zola')")
cursor.execute("INSERT INTO writers(Name) VALUES('Truman Capote')")


with conn:
通过with关键字,Python解释器自动释放资源,同时也提供错误处理。


## 取得数据

! /usr/bin/env python

coding=utf-8

import MySQLdb as mdb

conn = mdb.connect("localhost", "testuser", "test623", "testdb")

with conn:
cursor = conn.cursor()
cursor.execute("select * from writers")

rows = cursor.fetchall()

for row in rows:
    print row
在本例中,我们取得writers表中的所有数据。

**fetchall()**方法得到所有的记录。它返回一个结果集。它是一个元祖的元祖。每一个内部的元祖都代表表的一行记录。


## 一个一个取得数据

! /usr/bin/env python

coding=utf-8

import MySQLdb as mdb

conn = mdb.connect("localhost", "testuser", "test623", "testdb")

with conn:
cursor = conn.cursor()
cursor.execute("select * from writers")

for i in range(cursor.rowcount):
    row = cursor.fetchone()
    print row[0], row[1]```

字典游标

MySQLdb模块有几种游标类型。默认的游标以元祖的元祖形式返回数据。当我们使用字典游标的时候,数据以Python字典的形式发送。我们可以以列名称的形式访问数据。

#! /usr/bin/env python
#coding=utf-8
import MySQLdb as mdb

conn = mdb.connect("localhost", "testuser", "test623", "testdb")

with conn:
    cursor = conn.cursor(mdb.cursors.DictCursor)
    cursor.execute("select * from writers limit 4")
    
    rows = cursor.fetchall()
    
    for row in rows:
        print row["Id"], row["Name"]

列的头部

接下来,我们展示如何打印列的头部。.

#! /usr/bin/env python
#coding=utf-8
import MySQLdb as mdb

conn = mdb.connect("localhost", "testuser", "test623", "testdb")

with conn:
    cursor = conn.cursor(mdb.cursors.DictCursor)
    cursor.execute("select * from writers limit 5")
    
    rows = cursor.fetchall()
    
    desc = cursor.description
    
    print "%s %3s" % (desc[0][0], desc[1][0])

预处理语句

我们开始编写预处理语句时候,我们使用占位符而不是直接在语句里面写值。预处理语句增强了安全性和性能。Python数据库API规范建议了5种不同的方法来建立预处理语句。MySQLDB支持其中一种, ANSI printf 格式代码.

#! /usr/bin/env python
#coding=utf-8
import MySQLdb as mdb

conn = mdb.connect("localhost", "testuser", "test623", "testdb")
with conn:
    cur = conn.cursor()
    cur.execute("update writers set name=%s where id=%s", ("Guy de manpasant", "4"))
    
    print "number of rows updated:", cur.rowcount

你可能感兴趣的:(MySQL Python指南)