Python2 中使用模块 MySQLdb 模块处理数据库的操作,在Python3中使用 PyMySQL

Python2 - 数据库的操作

1. MySQLdb 安装

yum -y install MySQL-python

2. MySQL 数据库操作

2.1 准备以下MySQL数据库环境,便于后面的实验

名称
host 192.168.0.30
port 3306
user dbuser
passowrd 123
database mydb
table mytable

2.2 简单实例

 1 #!/usr/bin/python
 2 import MySQLdb
 3
 4 # Open a database connection
 5 conn = MySQLdb.connect('192.168.0.30','dbuser','123','mydb')
 6
 7 # Create a cursor objec using cursor()
 8 cursor = conn.cursor()
 9
10 # SQL statement
11 sql = 'SHOW variables like "%char%"';
12
13 # Execute SQL statement using execute()
14 cursor.execute(sql)
15
16 # Get data
17 data = cursor.fetchall()
18
19 print data
20
21 # Close database connection
22 cursor.close()

View Code

2.2 Insert 插入数据

 1 #!/usr/bin/python
 2 import MySQLdb
 3
 4 '''Insert'''
 5 # Open a database connection
 6 conn = MySQLdb.connect('192.168.0.30','dbuser','123','mydb')
 7
 8 # Create a cursor objec using cursor()
 9 cursor = conn.cursor()
10
11 # SQL statement
12 sql = 'INSERT INTO mytable(id,name) VALUES(2001,"Heburn"),(2002,"Jerry");'
13
14 try:
15     # Execute SQL statement using execute()
16     result = cursor.execute(sql)
17     # Commit
18     conn.commit()
19     print 'Insert',result,'records'
20 except:
21     # Rollback in case there is any error
22     conn.rollback()
23
24 # Close database connection
25 cursor.close()

View Code

2.3 Update 更新数据

 1 #!/usr/bin/python
 2 import MySQLdb
 3
 4 '''Update'''
 5 # Open a database connection
 6 conn = MySQLdb.connect('192.168.0.30','dbuser','123','mydb')
 7
 8 # Create a cursor objec using cursor()
 9 cursor = conn.cursor()
10
11 # SQL statement
12 sql = 'UPDATE mytable SET name="Lincoln" WHERE id = 2001;'
13
14 try:
15     # Execute SQL statement using execute()
16     result = cursor.execute(sql)
17     # Commit
18     conn.commit()
19     print 'Update',result,'records'
20 except:
21     # Rollback in case there is any error
22     conn.rollback()
23
24 # Close database connection
25 cursor.close()

View Code

2.4 删除数据

 1 #!/usr/bin/python
 2 import MySQLdb
 3
 4 '''Delete'''
 5 # Open a database connection
 6 conn = MySQLdb.connect('192.168.0.30','dbuser','123','mydb')
 7
 8 # Create a cursor objec using cursor()
 9 cursor = conn.cursor()
10
11 # SQL statement
12 sql = 'Delete from mytable WHERE id = 2001;'
13
14 try:
15     # Execute SQL statement using execute()
16     result = cursor.execute(sql)
17     # Commit
18     conn.commit()
19     print 'Delete',result,'records'
20 except:
21     # Rollback in case there is any error
22     conn.rollback()
23
24 # Close database connection
25 cursor.close()

View Code

2.5 查询数据

 1 #!/usr/bin/python
 2 import MySQLdb
 3
 4 '''Select'''
 5 # Open a database connection
 6 conn = MySQLdb.connect('192.168.0.30','dbuser','123','mydb')
 7
 8 # Create a cursor objec using cursor()
 9 cursor = conn.cursor()
10
11 # SQL statement
12 sql = 'SELECT id, name FROM mytable WHERE id = 2002;'
13
14 try:
15     # Execute SQL statement using execute()
16     cursor.execute(sql)
17
18     # Get all records
19     results = cursor.fetchall()
20     for row in results:
21         id = row[0]
22         name = row[1]
23         print 'id = %d, name = %s' % (id,name)
24
25 except:
26     print "Error: can't queray any data."
27
28 # Close database connection
29 cursor.close()

View Code

2.6 创建表

 1 #!/usr/bin/python
 2 import MySQLdb
 3
 4 '''Create table'''
 5 # Open a database connection
 6 conn = MySQLdb.connect('192.168.0.30','dbuser','123','mydb')
 7
 8 # Create a cursor objec using cursor()
 9 cursor = conn.cursor()
10
11 # SQL statement
12 sql = '''
13 CREATE TABLE mytable (
14     id int,
15     name char(20)
16 ) ENGINE = InnoDB DEFAULT CHARSET=utf8;
17 '''
18
19 try:
20     # Execute SQL statement using execute()
21     cursor.execute(sql)
22 except:
23     print "Error: can't Create table mytable."
24
25 # Close database connection
26 cursor.close()

View Code


Python3 - 数据库的操作

1. PyMySQL 安装

2. MySQL 数据库操作

2.1 准备以下MySQL数据库环境,便于后面的实验

名称
host 192.168.0.30
port 3306
user dbuser
passowrd 123
database mydb
table mytable

2.2 简单实例

import pymysql# Open the database connection
conn = pymysql.connect(host = '192.168.0.30',port = 3306,user = 'dbuser',password = '123',db = 'mydb',charset = 'utf8'
)# Create a cursor object using cursor()
cursor = conn.cursor()# SQL statement
sql = 'SELECT VERSION()'# Execute SQL query using execute()
cursor.execute(sql)# Get a piece single of data
data = cursor.fetchone()
print(data)# Close database connection
conn.close()

View Code

2.3 Insert 插入数据

 1 # Insert
 2 conn = pymysql.connect('192.168.0.30','dbuser','123','mydb')
 3 cursor = conn.cursor()
 4 sql = 'insert into mytable(id,name) values(1001, "Andrew");'
 5 try:
 6     cursor.execute(sql)
 7     conn.commit()
 8 except:
 9     conn.rollback()
10
11 conn.close()

View Code

2.4 Update 更新数据

 1 # Update
 2 conn = pymysql.connect('192.168.0.30','dbuser','123','mydb')
 3 cursor = conn.cursor()
 4 sql = 'update mytable set name = "Heburn" where id = 1001;'
 5 try:
 6     cursor.execute(sql)
 7     conn.commit()
 8 except:
 9     conn.rollback()
10
11 conn.close()

View Code

2.5 Delete 删除数据

 1 # Delete
 2 conn = pymysql.connect('192.168.0.30','dbuser','123','mydb')
 3 cursor = conn.cursor()
 4 sql = 'delete from mytable where id = 1001;'
 5 try:
 6     cursor.execute(sql)
 7     conn.commit()
 8 except:
 9     conn.rollback()
10
11 conn.close()

View Code

2.6 Select 查询数据

fetchone() 获取查询结果集中的一行内容

fetchall() 获取查询结果集中的所有行内容

 1 # Database Query
 2 conn = pymysql.connect('192.168.0.30','dbuser','123','mydb')
 3 cursor = conn.cursor()
 4 sql = 'select * from mytable where id = 1001;'
 5 try:
 6     cursor.execute(sql)
 7     results = cursor.fetchall()
 8     for row in results:
 9         id = row[0]
10         name = row[1]
11         print("id = %d, name = %s" % (id,name))
12 except:
13     print('Error: unable to fetch data.')
14
15 conn.close()

View Code

转载于:https://www.cnblogs.com/zhubiao/p/8664801.html

Python - MySQL数据库操作相关推荐

  1. python mysql数据库操作grid控件_Python学习笔记_02:使用Tkinter连接MySQL数据库实现登陆注册功能...

    1 环境搭建 1.1 Python安装 本文具体实现部分Python环境:Python2.7.14,64位版本 附:配置PythonIDE,推荐PyCharm(具体IDE界面见下图),下载点击运行即可 ...

  2. Python Mysql 数据库操作

    2019独角兽企业重金招聘Python工程师标准>>> 本文实例讲述了python中MySQLdb模块用法.分享给大家供大家参考.具体用法分析如下: MySQLdb其实有点像php或 ...

  3. python爬虫开发数据库设计入门经典_Python3实现的爬虫爬取数据并存入mysql数据库操作示例...

    本文实例讲述了Python3实现的爬虫爬取数据并存入mysql数据库操作.分享给大家供大家参考,具体如下: 爬一个电脑客户端的订单.罗总推荐,抓包工具用的是HttpAnalyzerStdV7,与chr ...

  4. python操作数据库的几种方法_python对mysql数据库操作的三种不同方式

    原标题:python对mysql数据库操作的三种不同方式 |转载自:博客园 |原文链接:http://www.cnblogs.com/mryrs/p/6951008.html 先要说一下,在这个暑期如 ...

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

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

  6. C++、Python、Java的MySQL数据库操作

    C++.Python.Java 的MySQL数据库操作 简介 提供MySQL安装说明,以及在C++.Python.Java编程中的MySQL数据库环境配置,并且分别利用这三种语言对基础的MySQL数据 ...

  7. mysql 根据子查询的结果查询朱标_Python - MySQL数据库操作

    Python2 中使用模块 MySQLdb 模块处理数据库的操作,在Python3中使用 PyMySQL Python2 - 数据库的操作 1. MySQLdb 安装 yum -y install M ...

  8. python的数据库操作_Python对数据库操作

    Windows下安装MySQL-python linux下安装MySQL-python以连接MySQL: 解压后,进入目录下,执行python setup.py install 安装过程中,常会遇到的 ...

  9. Python MySQL数据库的连接以及基本操作

    Python MySQL数据库的连接以及基本操作 一.数据库的连接 1.直接连接 2.连接池连接 二. 数据库的基本操作 1.执行函数 2.创建数据表 3.删除表 4.插入函数 6.删除函数 7.状态 ...

最新文章

  1. 彻底理解ThreadLocal
  2. Android 应用安全性改进: 全面助力打造 零漏洞 应用
  3. Zookeeper学习笔记之 Zab协议(Zookeeper Atomic Broadcast)
  4. 串口的输出设置【原创】
  5. 解决对象转json字符串时对象属性不按对象属性顺序的问题
  6. VS如何安装到电脑上
  7. 《那些年啊,那些事——一个程序员的奋斗史》七
  8. 用JSDoc生成js文档
  9. oracle cpu 消耗,解决Oracle CPU高度消耗(100%)的数据库问题
  10. 【学习笔记】数理统计习题十二
  11. GAN实战——书法字体生成练习赛开始报名啦!
  12. 150本畅销书已选好,快来认领!!
  13. leetcode714-买卖股票的最佳时机含手续费
  14. 【CTO讲堂】支付接入开发的陷阱有多深? 京东支付
  15. Matlab导出图片格式调整
  16. Hadoop集群优化-关闭THP
  17. 板子ping不通主机
  18. 第八章 我国农村商品流通
  19. 我的世界服务器不显示计分板,我的世界-计分板指令用法详细图文教程
  20. DL/T 645多功能电能表通信协议测试方法

热门文章

  1. 五种应该避免的代码注释
  2. elasticsearch 第二篇(配置篇)
  3. Java程序员从笨鸟到菜鸟之(一百零六)java操作office和pdf文件(四)页面列表导出cvs,excel、pdf报表.
  4. PigPen:用Clojure写MapReduce Introducing PigPen: Map-Reduce for Clojure
  5. Hbase shell详情
  6. 常用python模块
  7. 深度学习目标检测系列:RCNN系列算法图解
  8. LeetCode--160--相交链表
  9. 添加nginx为系统服务(service nginx start/stop/restart)
  10. 从零开始学_JavaScript_系列(16)——CSSlt;3gt;(文本、对齐、圆角、盒模型、背景)...