Python操作三大主流数据库
Python操作三大主流数据库
- 网址:https://coding.imooc.com/learn/list/114.html
- 学会使用的技术栈:python flask redis mongoDB mysql
第1章 数据库简介
简单介绍Mysql、数据库简介、导学篇
第2章 mysql基础
XAMPP 集成好的 最流行的PHP开发环境
mac 版本的mysql 安装
https://www.cnblogs.com/myxq666/p/7787744.html
数据库调试代码
-- 数据库链接小测试
CREATE DATABASE `mydatabase`;
USE `mydatabase`;
CREATE TABLE `students`(
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, -- 【解释】 id 整数类型 不为空 自动增长
`name` VARCHAR(200) NOT NULL,
`nickmane` VARCHAR(200) NULL,
`sex` CHAR(20) NULL,
`in_time` DATETIME NULL
) DEFAULT CHARACTER SET utf8 ;
-- 插入一条语句
INSERT INTO `students` VALUE(1, 'sss', 's', '1', NOW())
-- 【解释】 id 整数类型 不为空 自动增长
INSERT INTO `students` VALUE(1, '张三', '三', '男', NOW())
INSERT INTO `students` VALUE(2, '张三', '三', '男', NOW())
INSERT INTO `students` VALUE(3, '张三', '三', '男', NOW())
INSERT INTO `students` VALUE(4, 'zhangsan', 'san', 'nan', NOW())
INSERT INTO `students` VALUE(5, 'sadsadsa', 'ewqewq', 'fleman', NOW())
select * from `students`
# -- coding: utf-8 --
import MySQLdb
class MysqlSearch(object): # 让MysqlSearch类继承object对象
def __init__(self): # 在初始化的时候调用
self.get_conn()
def get_conn(self): # 数据库链接
try:
self.conn = MySQLdb.connect(
host="localhost",
user="root",
passwd="ljc123456",
db="mydatabase",
port=3306,
charset='utf8'
)
except MySQLdb.Error as e:
print("Error : %s" % e)
def close_conn(self): # 关闭数据库
try:
if self.conn:
# 关闭链接
self.conn.close()
except MySQLdb.Error as e:
print("Error: %s" % e)
def get_more(self):
sql = "select * from `students`"
cursor = self.conn.cursor()
cursor.execute(sql)
rest = cursor.fetchall()
cursor.close()
return rest
def main():
obj = MysqlSearch()
re = obj.get_more()
print(re)
print(type(re))
obj.close_conn()
pass
if __name__ == '__main__':
main()
""" 数据库链接测试成功
问题1:
OperationalError: (2006, 'SSL connection error: SSL_CTX_set_tmp_dh failed')
把 127.0.0.1 换成 localhost
import MySQLdb
MySQLdb.connect(
host="localhost",
user="root",
passwd="ljc123456",
db="mydatabase",
port=3306,
charset='utf8'
)
import pymysql
pymysql.connect(
host="localhost",
user="root",
passwd="ljc123456",
db="mydatabase",
port=3306,
charset='utf8'
)
问题2:
<bound method MysqlSearch.get_more of <__main__.MysqlSearch object at 0x107922390>>
sql = "select * from `students`" 写成了 sql = "select * from `students`;"
"""
2-2 mysql图形化管理工具
- Mysql语法
- show databases; 查看所有数据库
- use baidu;使用某一个数据库
- show tables; 查看数据库的数据表
-
图形化的管理工具:
* Php my Admin
* Navicat for mysql
2-3 sql语法基础-创建并使用数据库 - DDL 数据定义语句
* CREATE table/database 创建
* ALTER table/database 修改
* DROP table/database 删除 -
DML 数据管理语句
* INSERT 增加
* DELETE 删除
* UPDATE 更新
* SELECT 查询
1.创建数据库
——[注释]创建并使用数据库
CREATE DATABASE `mydatabase`; 反引号
USE `mydatabase`;
一般对数据库的操作分为 只读 和 读写
当我们在修改的时候采用读写 一般用只读来查询数据
% 代表任何ip地址都可以访问
localhost 127.0.0.1
-- 新建数据库
CREATE DATABASE `school`;
-- 使用数据库
USE `school`;
-- 创建表格
CREATE TABLE `students`(
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, -- 【解释】 id 整数类型 不为空 自动增长
`name` VARCHAR(200) NOT NULL,
`nickmane` VARCHAR(200) NULL,
`sex` CHAR(1) NULL,
`in_time` DATETIME NULL
);
-- 常见类型: int char varchar datetime
-- CHAR(200) 即使你存一个字符它也要用200个字节,这样很浪费空间。
-- VARCHAR(200) 以实际用的内存为主
-- NOT NULL 不为空 必须得填写
-- NULL 可以为空
-- 注意后面有一个分号 ;
-- 数据库优化:mysql36条军规
2-4 sql语法基础-创建表
2-5 sql语法基础-插入和查询语句
-- 新建查询
-- 新建多条学生数据
-- 插入语句
USE `school`;
-- 创建表格
CREATE TABLE `students6`(
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, -- 【解释】 id 整数类型 不为空 自动增长
`name` VARCHAR(200) CHARACTER SET utf8 NOT NULL,
`nickmane` VARCHAR(200) CHARACTER SET utf8 NULL,
`sex` CHAR(20) CHARACTER SET utf8 NULL,
`in_time` DATETIME NULL
);
CREATE TABLE `students`(
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, -- 【解释】 id 整数类型 不为空 自动增长
`name` VARCHAR(200) NOT NULL,
`nickmane` VARCHAR(200) NULL,
`sex` CHAR(20) NULL,
`in_time` DATETIME NULL
) DEFAULT CHARACTER SET utf8 ;
-- 显示中文要加上默认设置
-- 插入一条语句
INSERT INTO `students` VALUE(1, 'sss', 's', '1', NOW())
-- 【解释】 id 整数类型 不为空 自动增长
INSERT INTO `students` VALUE(1, '张三', '三', '男', NOW())
INSERT INTO `students` VALUE(2, '张三', '三', '男', NOW())
INSERT INTO `students` VALUE(3, '张三', '三', '男', NOW())
INSERT INTO `students` VALUE(4, 'zhangsan', 'san', 'nan', NOW())
INSERT INTO `students` VALUE(5, 'sadsadsa', 'ewqewq', 'fleman', NOW())
INSERT INTO `students5` VALUE(2, 'zhang', 'san', '0', NOW())
INSERT INTO `students6` VALUE(2, '张三', '三', '0', NOW())
INSERT INTO `students6` VALUE(1, 'ssswqewq', 'sqw', '1wew', NOW())
INSERT INTO `students6` VALUE(3, 'ssswqewq', 'sqw', '1wew', NOW())
INSERT INTO `students6` (`name`, `nickmane`, `sex`, `in_time`) VALUE('张三三多条数数据插入', '三三s', '男', NOW());
INSERT INTO `students6` (`name`, `nickmane`) VALUE('张三3', '三2s');
-- 非空的记录是必须填写的。
-- 插入多条语句
-- 以分号;结尾 表示 一个语句
-- 多行出入的时候通常以逗号,分隔。
INSERT INTO `students6` (`name`, `nickmane`) VALUES
('张三X', '三X'),
('张三X1', '三X1'),
('张三X2', '三X2'),
('张三X3', '三X3'),
('张三X4', '三X4'),
('张三X5', '三X5'),
('张三X6', '三X6')
;
/* ---- 查询语句 ---- */
-- 查询表students6的所有数据的所有信息
SELECT * from `students6`;
-- 只查询数据的`name`以及 `nickmane`
SELECT `name`, `nickmane` FROM `students6`;
-- 查询所有性别为 男 的 数据信息
SELECT `name`, `nickmane` FROM `students6` WHERE `sex`='男';
SELECT `id`,`name`, `nickmane` FROM `students6` WHERE `sex`='男';
-- 排序
-- ASC 正序、DESC 倒序
SELECT `id`,`name`, `nickmane` FROM `students6` WHERE `sex`='男' ORDER BY `id` DESC;
/*
查询条件书写的顺序
SELECT FROM
WHERE
GROUP BY
HAVING
ORDER BY
LIMIT 翻页 有两个参数 表述数据的起始位置(数据的偏移量),第二个数字表示多少个数据一页
*/
SELECT `id`,`name`, `nickmane` FROM `students6` WHERE `sex`='男' ORDER BY `id` DESC LIMIT 0, 2;
SELECT `id`,`name`, `nickmane` FROM `students6` WHERE `sex`='男' ORDER BY `id` DESC LIMIT 2, 2;
SELECT `id`,`name`, `nickmane` FROM `students6` WHERE `sex`='男' ORDER BY `id` DESC LIMIT 4, 2;
2-6 sql语法基础-修改和删除数据
/* 修改和删除数据 修改: UPDATE 表 SET 修改的内容 WHERE 修改的哪些数据 注意:不加 WHERE 条件 就是将所有数据修改 删除: DELETE FROM 表 WHERE 条件 注意:不加 WHERE 条件 就是将所有数据删除 */ -- 将不是男的性别设为女 UPDATE `students6` SET `sex` = '女' WHERE `sex` != '男'; UPDATE `students6` SET `sex` = '女' WHERE `sex` IS NULL; -- 将所有男生删除 DELETE FROM `students6` WHERE `sex` = '男'; -- 表中的数据全部删除 DELETE FROM `students6`;
2-7 设计新闻表
ID: 新闻的唯一标示
title:新闻的标题
content:新闻的内容
created_at:新闻添加的时间
types:新闻的类型
image:新闻的缩略图
author:作者
view_count:浏览量
is_valid:删除标记 新闻是否有效
删除:
物理删除:在数据库中直接将数据删除掉
逻辑删除:is_value 是否有效 ,有效1,无效0
第3章 python API
3-1 环境配置以及依赖安装
1.mysqlclient 1.3.12的支持
MySQL-5.5 through 5.7 and Python 2.7, 3.4+ are currently supported. PyPy is supported too.
lijuncheng@lijunchengdeMacBook-Pro ~ $ pip install mysqlclient
Collecting mysqlclient
Downloading mysqlclient-1.3.12.tar.gz (89kB)
100% |████████████████████████████████| 92kB 98kB/s
Building wheels for collected packages: mysqlclient
Running setup.py bdist_wheel for mysqlclient ... done
Stored in directory: /Users/lijuncheng/Library/Caches/pip/wheels/df/bb/60/bf7c315cbe163515db1c846e4ffa5557dd785c82e82f3492e8
Successfully built mysqlclient
Installing collected packages: mysqlclient
Successfully installed mysqlclient-1.3.12
2.验证是否安装成功
lijuncheng@lijunchengdeMacBook-Pro ~ $ python Python 2.7.13 |Anaconda custom (x86_64)| (default, Sep 21 2017, 17:38:20) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb >>>
3.python的虚拟环境 virtualenv python虚拟沙盒
多python环境
3-2 python链接mysql数据库
1.使用python连接数据库
连接到数据库之后,要关闭数据库。
3-3 python查询mysql数据库
# -- coding: utf-8 --
import MySQLdb
#中文输出. 只是为了在控制台上显示,字符的类型是正确的。
def chinese_output(str_tuple):
for i in range(len(str_tuple)):
print str_tuple[i]
pass
#将获取链接封装成calss
class MysqlSearch(object): # 让MysqlSearch类继承object对象
def __init__(self): # 在初始化的时候调用
self.get_conn()
def get_conn(self): # 数据库链接
try:
self.conn = MySQLdb.connect(
host = "127.0.0.1",
user = "root",
passwd = "admin123",
db = "news",
port = 3306,
charset = 'utf8'
)
except MySQLdb.Error as e:
print "Error : %s" % e
def close_conn(self): #关闭数据库
try:
if self.conn:
# 关闭链接
self.conn.close()
except MySQLdb.Error as e:
print "Error: %s" % e
def get_one(self): #查询一条数据
""" 流程:"""
# 1.准备SQL
sql = "SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;"
# 2.找到cursor
cursor = self.conn.cursor()
# 3.执行SQL
cursor.execute(sql, ("本地", ))
# 这边传的参数是一个元组
# print cursor.rowcount # 一共多少行
# print cursor.description
# 4.拿到结果
# rest = cursor.fetchone() # 就查询一体哦啊结果
rest = dict(zip([k[0] for k in cursor.description], cursor.fetchone()))
# 5.处理数据
#print rest
#print rest['title']
# 6.关闭cursor链接 两个关闭
cursor.close()
self.close_conn()
return rest
def get_more(self):
sql = "SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;"
cursor = self.conn.cursor()
cursor.execute(sql, ("本地", ))
# 多条数据获取的应该是一个list
# 列表推倒式子
rest = [dict(zip([k[0] for k in cursor.description], row))
for row in cursor.fetchall() ]
cursor.close()
self.close_conn()
return rest
# 多条数据换页
def get_more_page(self, page, page_size):
# 页面换算
offset = (page - 1) * page_size # 启始页面
sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC LIMIT %s, %s;'
cursor = self.conn.cursor()
# 将数字转换为字符. 不用转换。 瞎忙活。
# offset_str = str(offset)
# page_size_str = str(page_size)
cursor.execute(sql, ('本地', offset, page_size, ))
# 多条数据获取的应该是一个list
# 列表推倒式子
rest = [dict(zip([k[0] for k in cursor.description], row))
for row in cursor.fetchall() ]
cursor.close()
self.close_conn()
return rest
def main():
obj = MysqlSearch()
#单个结果输出
rest = obj.get_one()
print rest['title']
#多个结果删除。list
rest_more = obj.get_more()
for item in rest_more:
print item
print '-----------------------------------------------------------------------'
#分页输出
rest_more_page = obj.get_more_page(1,1)
for item in rest_more_page:
print item
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
if __name__ == '__main__':
main()
3-4 python更新mysql数据
# -- coding: utf-8 --
import MySQLdb
#中文输出. 只是为了在控制台上显示,字符的类型是正确的。
def chinese_output(str_tuple):
for i in range(len(str_tuple)):
print str_tuple[i]
pass
#将获取链接封装成calss
class MysqlSearch(object): # 让MysqlSearch类继承object对象
def __init__(self): # 在初始化的时候调用
self.get_conn()
def get_conn(self): # 数据库链接
try:
self.conn = MySQLdb.connect(
host = "127.0.0.1",
user = "root",
passwd = "admin123",
db = "news",
port = 3306,
charset = 'utf8'
)
except MySQLdb.Error as e:
print "Error : %s" % e
def close_conn(self): #关闭数据库
try:
if self.conn:
# 关闭链接
self.conn.close()
except MySQLdb.Error as e:
print "Error: %s" % e
def get_one(self): #查询一条数据
""" 流程:"""
# 1.准备SQL
sql = "SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;"
# 2.找到cursor
cursor = self.conn.cursor()
# 3.执行SQL
cursor.execute(sql, ("本地", ))
# 这边传的参数是一个元组
# print cursor.rowcount # 一共多少行
# print cursor.description
# 4.拿到结果
# rest = cursor.fetchone() # 就查询一体哦啊结果
rest = dict(zip([k[0] for k in cursor.description], cursor.fetchone()))
# 5.处理数据
#print rest
#print rest['title']
# 6.关闭cursor链接 两个关闭
cursor.close()
self.close_conn()
return rest
def get_more(self):
sql = "SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;"
cursor = self.conn.cursor()
cursor.execute(sql, ("本地", ))
# 多条数据获取的应该是一个list
# 列表推倒式子
rest = [dict(zip([k[0] for k in cursor.description], row))
for row in cursor.fetchall() ]
cursor.close()
self.close_conn()
return rest
# 多条数据换页
def get_more_page(self, page, page_size):
# 页面换算
offset = (page - 1) * page_size # 启始页面
sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC LIMIT %s, %s;'
cursor = self.conn.cursor()
# 将数字转换为字符. 不用转换。 瞎忙活。
# offset_str = str(offset)
# page_size_str = str(page_size)
cursor.execute(sql, ('本地', offset, page_size, ))
# 多条数据获取的应该是一个list
# 列表推倒式子
rest = [dict(zip([k[0] for k in cursor.description], row))
for row in cursor.fetchall() ]
cursor.close()
self.close_conn()
return rest
def add_one(self):
"""事务处理"""
try:
# 准备SQL
sql =(
"INSERT INTO `news` (`title`, `image`, `content`, `types`, `is_valid`) VALUE "
"( %s, %s, %s, %s, %s );"
)
# 出现换行的时候用一个元组扩起来。 应用双引号扩起来
# 获取链接和cursor
cursor = self.conn.cursor()
# 执行SQL
cursor.execute(sql, ('标题7','0122.png', '新闻内容22', '推荐', 1))
cursor.execute(sql, ('标题8','0122.png', '新闻内容22', '推荐', 'ss'))
# 错误
# 提交数据到数据库
""" 如果不提交的事务的话。就是 已经提交多数据库 但是没有被保存 """
# 提交事务
self.conn.commit()
# 关闭cursor
cursor.close()
except :
print "Error"
# self.conn.commit() # 部分提交
self.conn.rollback() # 回滚
# 关闭链接
self.close_conn()
# 多选 + / 多行注释
def main():
obj = MysqlSearch()
#单个结果输出
# rest = obj.get_one()
# print rest['title']
#多个结果删除。list
# rest_more = obj.get_more()
# for item in rest_more:
# print item
# print '-----------------------------------------------------------------------'
#分页输出
# rest_more_page = obj.get_more_page(1,1)
# for item in rest_more_page:
# print item
# print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
obj.add_one()
if __name__ == '__main__':
main()