python3操作mysql教程

一、下载安装配置

1. python3

Python3下载网址:http://www.python.org/getit/

当前最新版本是python3.2,下载地址是

http://www.python.org/ftp/python/3.2.3/python-3.2.3.msi

安装过程就不用说了,默认安装到C:Python32目录中。

安装好后,将安装目录C:Python32添加到环境变量中。然后打开命令提示符窗口,输入python,如果能返回python版本说明安装成功以及环境变量设置成功。

C:>python
Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 

2. MySQL

MySQL下载地址:http://www.mysql.com/downloads/mysql/

MySQL有很多种类型的版本,这里我们选择MySQL Community Server,最新版本5.5.25a

下载地址:http://cdn.mysql.com/Downloads/MySQL-5.5/mysql-5.5.25a-win32.msi

安装过程有点复杂,可以参考MySQL安装图解:

http://wenku.baidu.com/view/fe9b292e4b73f242336c5fe9.html

 注意,务必将MySQL的编码设成utf8

安装完成后需要对MySQL配置,这里我配置其用户名为root,密码Welcome123。

使用命令登录mysql,安装成功

C:>mysql -u root -p
Enter password: **********
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 10
Server version: 5.5.25a MySQL Community Server (GPL)

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

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

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

mysql>

这里我们创建一个名为txw1958的数据库。

mysql> create database txw1958;
Query OK, 1 row affected (0.03 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
| txw1958            |
+--------------------+
6 rows in set (0.00 sec)

3. MySQL-python模块

MySQL-python是MySQL用于python的数据库接口。目前支持python2.7和python3.2。

下载页面:http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python,找到MySQL-python-1.2.3.win32-py3.2.‌exe  

直接下载地址:http://www.lfd.uci.edu/~gohlke/pythonlibs/5jtpwme9/MySQL-python-1.2.3.win32-py3.2.exe

 

安装过程中能自动寻找到python3.2的安装目录,并安装到该目录下面。

 

安装完成后,在python中import MySQLdb,如果没有报错,则表示安装成功。

>>> import MySQLdb
>>> 

二、使用python3操作MySQL

以下是一个python3操作MySQL5.5的一个示例,其中包括连接MySQL,创建数据库,创建表格,插入/查询数据功能:

# -*- coding: utf-8 -*-
# author: txw1958
# website: http://www.cnblogs.com/txw1958/

import MySQLdb

#连接
cxn = MySQLdb.Connect(host = '127.0.0.1', user = 'root', passwd = 'Welcome123')
#游标
cur = cxn.cursor()

try:
    cur.execute("DROP DATABASE txw1958")
except Exception as e:
    print(e)
finally:
    pass

#创建数据库
cur.execute("CREATE DATABASE txw1958")
cur.execute("USE txw1958")

#创建表
cur.execute("CREATE TABLE users (id INT, name VARCHAR(8))")
#插入
cur.execute("INSERT INTO users VALUES(1, 'www'),(2, 'cnblogs'),(3, 'com'),(4, 'txw1958')")
#查询
cur.execute("SELECT * FROM users")
for row in cur.fetchall():
    print('%s	%s' %row)

#关闭
cur.close()
cxn.commit()
cxn.close()

关于MySQLdb的介绍和API请参考 http://mysql-python.sourceforge.net/MySQLdb.html

运行结果如下:

C:>python py3-mysql.py
1       www
2       cnblogs
3       com
4       txw1958

C:>

附MySQLdb的相关资料

1.引入MySQLdb库

import MySQLdb

2.和数据库建立连接

conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable",charset="utf8")

提供的connect方法用来和数据库建立连接,接收数个参数,返回连接对象.

比较常用的参数包括

host:数据库主机名.默认是用本地主机.

user:数据库登陆名.默认是当前用户.

passwd:数据库登陆的秘密.默认为空.

db:要使用的数据库名.没有默认值.

port:MySQL服务使用的TCP端口.默认是3306.

charset:数据库编码.

更多关于参数的信息可以查这里

http://mysql-python.sourceforge.net/MySQLdb.html

然后,这个连接对象也提供了对事务操作的支持,标准的方法

commit() 提交

rollback() 回滚

3.执行sql语句和接收返回值

cursor=conn.cursor()

n=cursor.execute(sql,param)

首先,我们用使用连接对象获得一个cursor对象,接下来,我们会使用cursor提供的方法来进行工作.这些方法包括两大类:1.执行命令,2.接收返回值

cursor用来执行命令的方法:

callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数

execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数

executemany(self, query, args):执行单条sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数

nextset(self):移动到下一个结果集

cursor用来接收返回值的方法:

fetchall(self):接收全部的返回结果行.

fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.

fetchone(self):返回一条结果行.

scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果mode='absolute',则表示从结果集的第一行移动value条.

下面的代码是一个完整的例子.

#使用sql语句,这里要接收的参数都用%s占位符.要注意的是,无论你要插入的数据是什么类型,占位符永远都要用%s

sql="insert into cdinfo values(%s,%s,%s,%s,%s)"

#param应该为tuple或者list

param=(title,singer,imgurl,url,alpha)

#执行,如果成功,n的值为1

n=cursor.execute(sql,param)

#再来执行一个查询的操作

cursor.execute("select * from cdinfo")

#我们使用了fetchall这个方法.这样,cds里保存的将会是查询返回的全部结果.每条结果都是一个tuple类型的数据,这些tuple组成了一个tuple

cds=cursor.fetchall()

#因为是tuple,所以可以这样使用结果集

print cds[0][3]

#或者直接显示出来,看看结果集的真实样子

print cds

#如果需要批量的插入数据,就这样做

sql="insert into cdinfo values(0,%s,%s,%s,%s,%s)"

#每个值的集合为一个tuple,整个参数集组成一个tuple,或者list

param=((title,singer,imgurl,url,alpha),(title2,singer2,imgurl2,url2,alpha2))

#使用executemany方法来批量的插入数据.这真是一个很酷的方法!

n=cursor.executemany(sql,param)

4.关闭数据库连接

需要分别的关闭指针对象和连接对象.他们有名字相同的方法

cursor.close()

conn.close()