您的位置:首页 > 编程语言 > Python开发

Python操作MySQL数据库

2016-05-22 12:04 344 查看
今天分享一下Python操作MySQL数据库相关的知识点。

安装必需品

我这里安装的是 Python2.7

MySQL5.6版本

数据库连接MySQL-python-1.2.3.win-amd64-py2.7

这个版本的我在Sourceforge上面找了很久才找到,一定要注意是安装的32位还是64位.链接如下:终极链接层

测试一下

打开命令行,若出现如下:

Microsoft Windows [版本 6.1.7600]
版权所有 (c) 2009 Microsoft Corporation。保留所有权利。

C:\Users\Administrator>python
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:40:30) [MSC v.1500 64 bit (
AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>>


就说明安装好了。

如果是采取zip文件安装的话,需要cd到相关的目录,使用
python setup.py install
。来进行安装,当然也可以借助pip这款神器咯。

数据库准备

在MySQL中创建我们待会要进行测试的数据库。

Server version: 5.6.24-log MySQL Community Server (GPL)

Copyright (c) 2000, 2015, 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.

mysql> show databases
-> ;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hibernate          |
| mybatis            |
| mysql              |
| performance_schema |
| practice           |
| sakila             |
| test               |
| world              |
+--------------------+

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

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hibernate          |
| mybatis            |
| mysql              |
| performance_schema |
| practice           |
| python             |
| sakila             |
| test               |
| world              |
+--------------------+

mysql> use python
Database changed


Python 代码测试

下面就借助一个简单的小例子来进行演示咯。

#coding:UTF-8

import MySQLdb

conn = MySQLdb.connect(
host='localhost',
port = 3306, # 切记这里是整数,而不是字符串!!!
user = 'root',
passwd = 'mysql',
db = 'python',
)

curs = conn.cursor()
# 创建一张数据库中的表
curs.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")

# 插入一条数据的记录
# curs.execute("insert into student values('2','Mark','Class 3','20')")

# 修改查询条件的数据 (这条语句不知道为什么,我的控制台执行的时候出错了。欢迎批评指正)
# curs.execute("update student set class='Class 14' where name ='Mark'")

# 删除查询条件的数据
# curs.execute("delete from student where age ='20'")

curs.close()
conn.commit()
conn.close()


下面分别来讲一讲每一个命令的具体的功能

// 创建一张名为student的表结构
curs.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")

// 查看数据库可见,那个db_test表是本人之前自己创建的

mysql> show tables;
+------------------+
| Tables_in_python |
+------------------+
| db_test          |
+------------------+
1 row in set (0.00 sec)

mysql> show tables;
+------------------+
| Tables_in_python |
+------------------+
| db_test          |
| student          |
+------------------+
2 rows in set (0.00 sec)

mysql>


curs.execute("insert into student values('2','Mark','Class 3','20')")

// 查看数据库结果
mysql> select * from student;
+------+------+---------+------+
| id   | name | class   | age  |
+------+------+---------+------+
|    2 | Mark | Class 3 | 20   |
+------+------+---------+------+
1 row in set (0.00 sec)
·
·
·
·
·
·


进阶版

使用纯的SQL语句进行操作,很是麻烦。类似于Java的PreparedStatement的方式,Python也有类似于占位符的形式来操作数据库。如下:

#coding=utf-8
import MySQLdb

conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
)
cur = conn.cursor()

#插入一条数据
sqli="insert into student values(%s,%s,%s,%s)"
cur.execute(sqli,('3','Huhu','2 year 1 class','7'))

#一次插入多条记录
sqli="insert into student values(%s,%s,%s,%s)"
cur.executemany(sqli,[
('3','Tom','1 year 1 class','6'),
('3','Jack','2 year 1 class','7'),
('3','Yaheng','2 year 2 class','7'),
])

# 获取表中的数据
cur.execute("select * from student")
cur.fetchone()

# fetchone()方法可以帮助我们获得表中的数据,可是每次执行cur.fetchone() 获得的数据都不一样,换句话说我没执行一次,游标会从表中的第一条数据移动到下一条数据的位置,所以,我再次执行的时候得到的是第二条数据。
# scroll(0,'absolute') 方法可以将游标定位到表中的第一条数据。

#获得表中有多少条数据
aa=cur.execute("select * from student")
print aa

#打印表中的多少数据
info = cur.fetchmany(aa)
for ii in info:
print ii

cur.close()
conn.commit()
conn.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: