python连接mysql的操作
一,安装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连接mysql的操作的更多相关文章
- Python连接MySQL数据库操作
一.创建数据库及表 CREATE DATABASE testdb; USE testdb; CREATE TABLE `tb_user` ( `id` INT (11) NOT NULL AUTO_I ...
- python 连接mysql数据库操作
import pymysql.cursors # 连接数据库 connect = pymysql.Connect( host='localhost', port=3306, user='root', ...
- python连接mysql操作(1)
python连接mysql操作(1) import pymysql import pymysql.cursors # 连接数据库 connect = pymysql.Connect( host='10 ...
- python对mysql数据库操作的三种不同方式
首先要说一下,在这个暑期如果没有什么特殊情况,我打算用python尝试写一个考试系统,希望能在下学期的python课程实际使用,并且尽量在此之前把用到的相关技术都以分篇博客的方式分享出来,有想要交流的 ...
- Python连接MySQL数据库的多种方式
上篇文章分享了windows下载mysql5.7压缩包配置安装mysql 后续可以选择 ①在本地创建一个数据库,使用navicat工具导出远程测试服务器的数据库至本地,用于学习操作,且不影响测试服务器 ...
- pymysql模块使用---Python连接MySQL数据库
pymysql模块使用---Python连接MySQL数据库 浏览目录 pymysql介绍 连接数据库 execute( ) 之 sql 注入 增删改查操作 进阶用法 一.pymysql介绍 1.介绍 ...
- python连接mysql服务端
python连接mysql的客户端 import pymysql # 导入模块 conn = pymysql.connect( host='127.0.0.1', # 主机模块 port=3306, ...
- 【数据驱动】python之mysql的操作
1.准备工作 在本篇中,我们使用python版本为python3.7.在python3中,连接mysql数据库我们需要使用pymysql这个第三方库.我们可以直接使用pip命令来安装,安装的命令为: ...
- python连接MySQL/redis/mongoDB数据库的简单整理
python连接mysql 用python操作mysql,你必须知道pymysql 代码示意: import pymysql conn = pymysql.connect(host='127.0.0. ...
随机推荐
- YTU 2906: 多重继承 日期与时间
2906: 多重继承 日期与时间 时间限制: 1 Sec 内存限制: 128 MB 提交: 240 解决: 190 题目描述 在空缺的地方补全代码,只需提交补全部分即可 请用C++方式提交 #in ...
- 2-6 Opencv模块组织结构
https://opencv.org/releases.html https://sourceforge.net/projects/opencvlibrary/files/opencv-win/3.4 ...
- 使用 dynamic 标记解析JSON字符串(转)
http://www.cnblogs.com/taotaodetuer/p/4171327.html string jsonStr = "{\"data\": {\&qu ...
- bzoj 1042: [HAOI2008]硬币购物【dp】
设f[i]为凑i元的方案数,这个随便dp一下就行了 然后处理限制,我们考虑用容斥,也就是4个超限-3个超限+2个超限-1个超限,这里用状压枚举一下,然后i硬币超限就当做选了d[i]+1个,在s里减去, ...
- bzoj 1502 月下柠檬树【Simpson积分】
投影到地面之后,会发现圆形在平行光下面积和形状是不会变的,也就是所要求的图形是若干个圆和把相邻两个圆连起来的公切线所组成的. 公切线和圆间距瞎求一下就行,注意要去掉被完全覆盖的圆 然后simpson即 ...
- Ubuntu 18.04 LTS 系统设置打不开了
在更换软件源后,安装了vim 和chrome,chrome很顺利,但是安装vim的时候后就显示有问题了,有的依赖版本不对,嫌版本太高,卸载后再装可以. 安装了python和python2 依旧是有些依 ...
- Spring + MyBaits 日志初始化两遍的问题
偶然发现一个问题,记录一下以备查询. 问题:系统启动时发现日志初始化了两次 14:28:04.798 [main] DEBUG org.apache.ibatis.logging.LogFactory ...
- 暑期训练狂刷系列——poj 3264 Balanced Lineup(线段树)
题目连接: http://poj.org/problem?id=3264 题目大意: 有n个数从1开始编号,问在指定区间内,最大数与最小数的差值是多少? 解题思路: 在节点中存储max,min,然后查 ...
- Hibernate3中重复引用hbm文件错误信息记录
Hibernate3中重复引用hbm文件错误信息记录. 八月 ::, ERROR - Context initialization failed org.springframework.beans.f ...
- poj1715Hexadecimal Numbers(数位dp)
链接 好久没写这种逐位计数的了. 先统计出总的数 ,s-n+1,倒着计算的 ,感觉倒着比较符合计算方式,总数为15*A(15,i) (1=<i<=8) 也就是1-8长度所有的排列总数 然后 ...