python中使用mysql数据库详细介绍


Posted in Python onMarch 27, 2015

一、安装mysql

如果是windows 用户,mysql 的安装非常简单,直接下载安装文件,双击安装文件一步一步进行操作即可。

Linux 下的安装可能会更加简单,除了下载安装包进行安装外,一般的linux 仓库中都会有mysql ,我们只需要通过一个命令就可以下载安装:

Ubuntu\deepin

>>sudo apt-get install mysql-server
>>Sudo apt-get install  mysql-client

centOS/redhat
>>yum install mysql

二、安装MySQL-python

要想使python可以操作mysql 就需要MySQL-python驱动,它是python 操作mysql必不可少的模块。

下载地址:https://pypi.python.org/pypi/MySQL-python/

下载MySQL-python-1.2.5.zip 文件之后直接解压。进入MySQL-python-1.2.5目录:

>>python setup.py install

三、测试

测试非常简单,检查MySQLdb 模块是否可以正常导入。

fnngj@fnngj-H24X:~/pyse$ python 

Python 2.7.4 (default, Sep 26 2013, 03:20:56) 

[GCC 4.7.3] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> import MySQLdb

没有报错提示MySQLdb模块找不到,说明安装OK ,下面开始使用python 操作数据库之前,我们有必要来回顾一下mysql的基本操作:

四、mysql 的基本操作

$ mysql -u root -p  (有密码时)

$ mysql -u root     (无密码时)
mysql> show databases;  // 查看当前所有的数据库

+--------------------+

| Database           |

+--------------------+

| information_schema |

| csvt               |

| csvt04             |

| mysql              |

| performance_schema |

| test               |

+--------------------+

6 rows in set (0.18 sec)
mysql> use test;   //作用与test数据库

Database changed

mysql> show tables;   //查看test库下面的表

Empty set (0.00 sec)
//创建user表,name 和password 两个字段

mysql> CREATE  TABLE  user (name VARCHAR(20),password VARCHAR(20));  Query OK, 0 rows affected (0.27 sec)
//向user表内插入若干条数据

mysql> insert into user values('Tom','1321');

Query OK, 1 row affected (0.05 sec)
mysql> insert into user values('Alen','7875');

Query OK, 1 row affected (0.08 sec)
mysql> insert into user values('Jack','7455');

Query OK, 1 row affected (0.04 sec)
//查看user表的数据

mysql> select * from user;

+------+----------+

| name | password |

+------+----------+

| Tom  | 1321     |

| Alen | 7875     |

| Jack | 7455     |

+------+----------+

3 rows in set (0.01 sec)
//删除name 等于Jack的数据

mysql> delete from user where name = 'Jack';

Query OK, 1 rows affected (0.06 sec)
//修改name等于Alen 的password 为 1111

mysql> update user set password='1111' where name = 'Alen';

Query OK, 1 row affected (0.05 sec)

Rows matched: 1  Changed: 1  Warnings: 0
//查看表内容

mysql> select * from user;

+--------+----------+

| name   | password |

+--------+----------+

| Tom    | 1321     |

| Alen   | 1111     |

+--------+----------+

3 rows in set (0.00 sec)

五、python 操作mysql数据库基础

#coding=utf-8

import MySQLdb
conn= MySQLdb.connect(

        host='localhost',

        port = 3306,

        user='root',

        passwd='123456',

        db ='test',

        )

cur = conn.cursor()
#创建数据表

#cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
#插入一条数据

#cur.execute("insert into student values('2','Tom','3 year 2 class','9')")


#修改查询条件的数据

#cur.execute("update student set class='3 year 1 class' where name = 'Tom'")
#删除查询条件的数据

#cur.execute("delete from student where age='9'")
cur.close()

conn.commit()

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

Connect() 方法用于创建数据库的连接,里面可以指定参数:用户名,密码,主机等信息。

这只是连接到了数据库,要想操作数据库需要创建游标。

>>> cur = conn.cursor()

通过获取到的数据库连接conn下的cursor()方法来创建游标。
>>> cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")

通过游标cur 操作execute()方法可以写入纯sql语句。通过execute()方法中写如sql语句来对数据进行操作。
>>>cur.close()

cur.close() 关闭游标
>>>conn.commit()

conn.commit()方法在提交事物,在向数据库插入一条数据时必须要有这个方法,否则数据不会被真正的插入。
>>>conn.close()

Conn.close()关闭数据库连接

六、插入数据

通过上面execute()方法中写入纯的sql语句来插入数据并不方便。如:

>>>cur.execute("insert into student values('2','Tom','3 year 2 class','9')")

我要想插入新的数据,必须要对这条语句中的值做修改。我们可以做如下修改:
#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'))
cur.close()

conn.commit()

conn.close()

假如要一次向数据表中插入多条值呢?

#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.executemany(sqli,[

    ('3','Tom','1 year 1 class','6'),

    ('3','Jack','2 year 1 class','7'),

    ('3','Yaheng','2 year 2 class','7'),

    ])
cur.close()

conn.commit()

conn.close()

executemany()方法可以一次插入多条值,执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数。

七、查询数据

也许你已经尝试了在python中通过

>>>cur.execute("select * from student")

来查询数据表中的数据,但它并没有把表中的数据打印出来,有些失望。

来看看这条语句获得的是什么

>>>aa=cur.execute("select * from student")
>>>print aa
5

它获得的只是我们的表中有多少条数据。那怎样才能获得表中的数据呢?进入python shell
>>> import MySQLdb

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

>>> cur = conn.cursor()

>>> cur.execute("select * from student")

5L

>>> cur.fetchone()

(1L, 'Alen', '1 year 2 class', '6')

>>> cur.fetchone()

(3L, 'Huhu', '2 year 1 class', '7')

>>> cur.fetchone()

(3L, 'Tom', '1 year 1 class', '6')

...

>>>cur.scroll(0,'absolute')

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

scroll(0,'absolute') 方法可以将游标定位到表中的第一条数据。

还是没解决我们想要的结果,如何获得表中的多条数据并打印出来呢?

#coding=utf-8

import MySQLdb
conn= MySQLdb.connect(

        host='localhost',

        port = 3306,

        user='root',

        passwd='123456',

        db ='test',

        )

cur = conn.cursor()
#获得表中有多少条数据

aa=cur.execute("select * from student")

print aa
#打印表中的多少数据

info = cur.fetchmany(aa)

for ii in info:

    print ii

cur.close()

conn.commit()

conn.close()

通过之前的print aa 我们知道当前的表中有5条数据,fetchmany()方法可以获得多条数据,但需要指定数据的条数,通过一个for循环就可以把多条数据打印出啦!执行结果如下:

5

(1L, 'Alen', '1 year 2 class', '6')

(3L, 'Huhu', '2 year 1 class', '7')

(3L, 'Tom', '1 year 1 class', '6')

(3L, 'Jack', '2 year 1 class', '7')

(3L, 'Yaheng', '2 year 2 class', '7')

[Finished in 0.1s]
Python 相关文章推荐
Python greenlet实现原理和使用示例
Sep 24 Python
python比较两个列表大小的方法
Jul 11 Python
浅谈python 里面的单下划线与双下划线的区别
Dec 01 Python
Python跨文件全局变量的实现方法示例
Dec 10 Python
numpy中的高维数组转置实例
Apr 17 Python
对python周期性定时器的示例详解
Feb 19 Python
Python 运行.py文件和交互式运行代码的区别详解
Jul 02 Python
使用python的turtle函数绘制一个滑稽表情
Feb 28 Python
使用Python3 poplib模块删除服务器多天前的邮件实现代码
Apr 24 Python
django和flask哪个值得研究学习
Jul 31 Python
python如何运行js语句
Sep 09 Python
Python语言中的数据类型-序列
Feb 24 Python
python获得两个数组交集、并集、差集的方法
Mar 27 #Python
Flask入门教程实例:搭建一个静态博客
Mar 27 #Python
Python中的高级数据结构详解
Mar 27 #Python
python中反射用法实例
Mar 27 #Python
Python中使用摄像头实现简单的延时摄影技术
Mar 27 #Python
python根据出生日期返回年龄的方法
Mar 26 #Python
python获取远程图片大小和尺寸的方法
Mar 26 #Python
You might like
如何用php获取文件名后缀
2013/06/09 PHP
自己写的php中文截取函数mb_strlen和mb_substr
2015/02/09 PHP
学习YUI.Ext 第二天
2007/03/10 Javascript
Bootstrap每天必学之基础排版
2015/11/20 Javascript
jQuery根据name属性进行查找的用法分析
2016/06/23 Javascript
HTML中setCapture、releaseCapture 使用方法浅析
2016/09/25 Javascript
jquery删除数组中重复元素
2016/12/05 Javascript
jQuery实现别踩白块儿网页版小游戏
2017/01/18 Javascript
JavaScript使用Ajax上传文件的示例代码
2017/08/10 Javascript
.vue文件 加scoped 样式不起作用的解决方法
2018/05/28 Javascript
vue项目使用微信公众号支付总结及遇到的坑
2018/10/23 Javascript
使用Angular Cli如何创建Angular私有库详解
2019/01/30 Javascript
Vue.js下拉菜单组件使用方法详解
2019/10/19 Javascript
layui清除radio的选中状态实例
2019/11/14 Javascript
js中Function引用类型常见有用的方法和属性详解
2019/12/11 Javascript
微信小程序绘制半圆(弧形)进度条
2020/11/18 Javascript
Python 返回汉字的汉语拼音
2009/02/27 Python
基于Python数据可视化利器Matplotlib,绘图入门篇,Pyplot详解
2017/10/13 Python
Python实现随机漫步功能
2018/07/09 Python
Python之使用adb shell命令启动应用的方法详解
2019/01/07 Python
python整合ffmpeg实现视频文件的批量转换
2019/05/31 Python
Python Lambda函数使用总结详解
2019/12/11 Python
基于python实现matlab filter函数过程详解
2020/06/08 Python
Html5剪切板功能的实现代码
2018/06/29 HTML / CSS
英国PC组件和在线电脑商店:SCAN
2019/04/18 全球购物
迪奥美国官网:Dior美国
2019/12/07 全球购物
西安众合通用.net笔试题
2013/03/18 面试题
客服部班长工作责任制
2014/02/25 职场文书
竞聘上岗演讲稿
2014/05/16 职场文书
2014应届本科生自我评价
2014/09/13 职场文书
晋江市人民政府党组群众路线教育实践活动整改方案
2014/10/25 职场文书
郭明义电影观后感
2015/06/08 职场文书
演讲比赛主持词
2015/06/29 职场文书
2016猴年开门红标语口号
2015/12/26 职场文书
Spring Data JPA使用JPQL与原生SQL进行查询的操作
2021/06/15 Java/Android
Python各协议下socket黏包问题原理
2022/04/12 Python