一,安装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 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/tianfen/p/6292476.html

python连接mysql的操作相关推荐

  1. python mysql 连接6_寒假学习进度-6(Python连接MySQL数据库)

    Python连接mysql和操作 软件:pycharm 开始在pycharm下面的Terminal中安装mysql时提醒pip版本不够,所以需要先升级一下pip python -m pip insta ...

  2. python连接MySQL并进行数据查询

    python连接MySQL并进行数据查询 #建立数据库的连接 mydb = mysql.connector.connect(host="0.0.0.0",user="ro ...

  3. python连接mysql数据库数据库_python如何连接mysql数据库

    先花点时间来说说一个程序怎么和数据库进行交互 1.和数据库建立连接 2.执行sql语句,接收返回值 3.关闭数据库连接 使用MySQLdb也要遵循上面的几步.让我们一步步的进行. 1.MySQL数据库 ...

  4. Python——Python连接MySQL数据库

    基本概念 PyMySQL:PyMySQL是封装了MySQL驱动的Python驱动,一个能使Python连接到MySQL的库. mysql-connector-python(MySQL Connecto ...

  5. Python连接MySQL数据库(pymysql),DataFrame写入 MySQL(create_engine)- Python代码

    模块安装 使用以下命令安装 PyMySQL: $ pip install PyMySQL 若系统不支持 pip,还可以这样安装: $ git clone https://github.com/PyMy ...

  6. python连接mysql数据库数据

    使用python连接mysql数据库数据,有以下两种读取数据的方式推荐. 一种是通过游标,及fetch系列方法进行操作,另一种是通过pandas的read_sql()进行读取并操作.各种方法各有优劣, ...

  7. Python连接MySQL、PostgreSQL数据库(简单便捷)

    一.安装库 Python连接MySQL.PostgreSQL数据库需要导入相关的模块,分别是"pymysql"和"psycopg2"模块,我们可以在Pychar ...

  8. Python封装MySQL数据库操作(pymysql)

    Python封装MySQL数据库操作(pymysql) # 连接MySQL class DbManager(object):# 构造函数def __init__(self):self.conn = N ...

  9. python连接mysql三种方式_用 Python 连接 MySQL 的几种方式详解

    每个学 Python 的都有必要学好一门数据库,不管你是做数据分析,还是网络爬虫,Web 开发.亦或是机器学习,你都离不开要和数据库打交道,而 MySQL 又是最流行的一种数据库,这篇文章介绍 Pyt ...

最新文章

  1. 更改mssql数据库的名字
  2. Python-OpenCV 杂项(一):图像绘制
  3. Spark Streaming初步使用以及工作原理详解
  4. 解决Linux下动态链接库失败的问题
  5. Qt Creator管理项目
  6. 64位ubuntu 12.04系统编译busybox遇到的问题处理办法
  7. 微型计算机原理上机实验改错,北京理工大学微机原理汇编语言上机实验题
  8. 15.使用using和try/finally来做资源清理
  9. java只修改变的字段_java注解之运行时修改字段的注解值操作
  10. 为iPhone 12上市做准备,台积电月底前投产A14 Bionic芯片
  11. ES6阮一峰读书笔记第二章变量的解构赋值
  12. NIO蔚来ET5/ET7电动汽车维修手册电路图用户手册技术资料
  13. 草根的91助手和它的同类们
  14. 「白帽黑客成长记」Windows提权基本原理(上)
  15. Python 中的列表(一)
  16. 计算机如何提高开机速度?
  17. 用计算机弹出记事本,win7电脑开机就会弹出Desktop.ini记事本怎么办?
  18. 物联网网关神器 Kong ( 四 )- 利用 Konga 来配置生产环境安全连接 Kong
  19. Mac上十个必备的效率软件
  20. Android 常用正则表达式

热门文章

  1. java无法编译加载主类_JAVA编译完毕运行时错误找不到或无法加载主类
  2. vfp 修改本机时间_借助novapdfPro 将VFP报表无感生成PDF文件
  3. c语言课程案例设计报告,C语言课程设计报告—范例解读.doc
  4. 20210803:AXI-Stream协议源码分析初探
  5. 20200701:力扣194周周赛上
  6. mysql怎么用sb文件_初识mysql数据库
  7. 任正非华为为什么暂不推出鸿蒙,任正非表示,华为的鸿蒙系统已经上网?惊喜吗...
  8. js字符串转换为json对象JSON.parse()及将json对象转为json字符串JSON.stringify()
  9. sunplus 8202v iop源代码阅读笔记——1
  10. 变身抓重点小能手:机器学习中的文本摘要入门指南 | 资源