侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

python使用mysql数据库示例代码

Python  /  管理员 发布于 7年前   131

一,安装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 linux2Type "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 changedmysql> 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 为 1111mysql> 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-8import 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-8import 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-8import 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 aa5

它获得的只是我们的表中有多少条数据。那怎样才能获得表中的数据呢?进入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-8import 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 iicur.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实现一个转存纯真IP数据库的脚本分享
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客