mysql的基本操作
python操作mysql之查询
python操作mysql之插入数据
python操作mysql之批量插入数据
python操作mysql之批量获取字典类型数据
python操作mysql之fetchone和获取自增ID

二,安装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 MySQLdbconn= 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 MySQLdbconn= 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 MySQLdbconn= 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 MySQLdbconn= 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]

转载于:https://www.cnblogs.com/muzinan110/p/4938559.html

python-mysql相关推荐

  1. python mysql 驱动安装

    为什么80%的码农都做不了架构师?>>>    安装组件: python 3.4 + django 1.7 + mysql connector driver 系统平台: window ...

  2. python mysql 转义方法

    最近用python做项目的时候用到了mysql,把用python抓取的一些是数据放到mysql里去,但是有个问题,因为从外面抓取的数据有带'等其他的不规则的数据,如果你直接调用插入数据的方法会提示报错 ...

  3. python + MySql 基本操作

    python + mysql数据库的链接 1.安装mysql pip install PySQLdb 2.连接数据库 # -*- coding: UTF-8 -*-import MySQLdb# 打开 ...

  4. python mysql数据库长连接_python 长连接 mysql数据库

    python 长连接数据库 python链接mysql中没有长链接的概念,但我们可以利用mysql的ping机制,来实现长链接功能 思路: 1 python mysql 的cping 函数会校验链接的 ...

  5. Python 基于python+mysql浅谈redis缓存设计与数据库关联数据处理

    基于python+mysql浅谈redis缓存设计与数据库关联数据处理 by:授客  QQ:1033553122 测试环境 redis-3.0.7 CentOS 6.5-x86_64 python 3 ...

  6. 第一节、Alex 讲解 python+mysql 交互;

    Python Mysql 交互 A.Alex 的语法展示: import MySQLdb try: conn=MySQL.connect(host='localhost',user='root',pa ...

  7. Python—Mysql—Dbvisualizer

    MySQLdb: https://pypi.python.org/pypi/MySQL-python/1.2.4 import MySQLdb 1.Download Connector/Python: ...

  8. 今日代码(200725)--数据录入(python+mysql)

    代码记录 数据录入(python+mysql) 前言 相比于200612代码增加了一个性别.运动员编号.运动员姓名字段. 代码 # -*- coding: utf-8 -*-import re imp ...

  9. kettle大于0的转换成1_第一期实训周:基于Python+MySQL+Kettle+R的某网站数据采集分析...

    ↓ 基于Python+MySQL+Kettle+R的 某网站数据采集分析 哈喽!各位学员们 咱们第一期课程就要开始了 下面划重点! 一 高校院系 齐鲁工业大学数学与统计学院应用统计系 二 实训日期 2 ...

  10. python MySQL 插入Elasticsearch

    一.需求分析 注意: 本环境使用 elasticsearch 7.0版本开发,切勿低于此版本 mysql 表结构 有一张表,记录的数据特别的多,需要将7天前的记录,插入到Elasticsearch中, ...

最新文章

  1. 未来之城,管理者可能不是人......
  2. 关于delphi 窑洞的关闭
  3. ajax提交Form
  4. Xamarin Anroid App访问网站失败
  5. (转)zookeeper理解
  6. Android Studio快捷键快速入门
  7. 使用iBatis数据映射框架吧
  8. vue watch高级用法
  9. [转载] json字符串转list_Python入门进阶教程JSON操作
  10. 全民 Transformer (一): Attention 在深度学习中是如何发挥作用的
  11. 快应用开发教程【02】--项目配置教程
  12. Tensorspace一款神奇的神经网络可视化应用
  13. JAVA字节流,字符流
  14. 西门子plc编程软件step 7 microwin smart下载指南
  15. 用C语言进行完数的判断(for循环和数组思想)
  16. 求车牌号问题(C语言程序设计)
  17. 云计算机教室优缺点,云教室和传统机房的区别,终于有人把它说清了
  18. AutoRunner 功能自动化测试项目实训之认识自动化测试工具AutoRunner(二)
  19. PR更改视频画布大小。PR剪裁视频。PR导出视频时的适应视屏大小都是啥意思啊?
  20. 单片机晶振电路的设计与计算

热门文章

  1. 用POST方式获取Radio Button是否被选中的信息
  2. hbase开发环境搭建及运行hbase小实例(HBase 0.98.3新api)
  3. JS 提交form表单
  4. gin构建包含模板的二进制文件
  5. golang中的strings.SplitAfter
  6. 抓包分析connect函数
  7. 【自由随想录(一)】
  8. Linux的企业-Mfs高可用corosync+pacemaker+fence+iscci
  9. joinColumns和inverseJoinColumns的使用方法
  10. 测试JdbcTemplate执行SQL语句和存储过程