标签:将不 解释 hang ret current pack 语句 http 成功
简单介绍Mysql、数据库简介、导学篇
XAMPP 集成好的 最流行的PHP开发环境
mac 版本的mysql 安装
https://www.cnblogs.com/myxq666/p/7787744.html
2-2 mysql图形化管理工具
图形化的管理工具:
* Php my Admin
* Navicat for mysql
2-3 sql语法基础-创建并使用数据库
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-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()
4-1 ORM简介
对象关系映射(Object Relational Mapping)
ORM的实现:
1.SqlObject
2.peewee
3.Django‘s ORM Django 框架
4.SQLAlchemy
doc document 文档
4-2 SQLAlchemy安装
DBAPI 对数据库的操作
SQLAlchemy 对数据库语言的封装
SQLAlchemy ORM核心的部分
安装:
lijuncheng@lijunchengdeMacBook-Pro ~ $ pip install SQLAlchemy
Requirement already satisfied: SQLAlchemy in ./anaconda2/lib/python2.7/site-packages
lijuncheng@lijunchengdeMacBook-Pro ~ $
测试
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 sqlalchemy
>>> sqlalchemy.__version__
‘1.1.13‘
4-3 ORM模型介绍
常见类型: Integer Float Boolean。ForeignKe Date/DateTime String
文档:http://docs.sqlalchemy.org/en/latest/core/
一个模型对应一张表
使用命令行创建表
lijuncheng@lijunchengdeMacBook-Pro ~/Code/MySQL数据库 代码/实战网易新闻 $ 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.
>>> from test_mysql_orm import News
>>> from test_mysql_orm import engine
>>> News.metadata.create_all(engine) # 创建news表
/Users/lijuncheng/anaconda2/lib/python2.7/site-packages/sqlalchemy/dialects/mysql/base.py:1569: Warning: (1287L, "‘@@tx_isolation‘ is deprecated and will be removed in a future release. Please use ‘@@transaction_isolation‘ instead")
cursor.execute(‘SELECT @@tx_isolation‘)
>>>
4-4 新建ORM模型
4-5 通过ORM新增数据到数据库
4-6 通过ORM查询数据
4-7 通过ORM修改删除数据
# -- coding: utf-8 --
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Table, Column, Integer, String, DateTime, Boolean
# 获取链接 Connecting
# engine = create_engine(‘mysql://root:admin123@localhost:3306/news_test‘)
# 插入中文出现错误解决
engine = create_engine(‘mysql://root:admin123@localhost:3306/news_test?charset=utf8‘)
# Declare a Mapping
# 获取基类
Base = declarative_base()
# 获取session对象
Session = sessionmaker(bind = engine)
#模型声明
class News(Base): # Base 是 ORM的一个基类 ,也就是说News类继承自Base
""" 新闻类 """
__tablename__ = ‘news‘
id = Column(Integer, primary_key = True) # 若数据为news_id id = Column(Interger, primaty_key = True)
title = Column(String(200), nullable = False)
content = Column(String(2000), nullable = False)
types = Column(String(10), nullable = False )
image = Column(String(300))
author = Column(String(20))
view_count = Column(Integer)
created_at = Column(DateTime)
is_valid = Column(Boolean)
"""
使用命令行创建表
lijuncheng@lijunchengdeMacBook-Pro ~/Code/MySQL数据库 代码/实战网易新闻 $ 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.
>>> from test_mysql_orm import News
>>> from test_mysql_orm import engine
>>> News.metadata.create_all(engine) # 创建news表
/Users/lijuncheng/anaconda2/lib/python2.7/site-packages/sqlalchemy/dialects/mysql/base.py:1569: Warning: (1287L, "‘@@tx_isolation‘ is deprecated and will be removed in a future release. Please use ‘@@transaction_isolation‘ instead")
cursor.execute(‘SELECT @@tx_isolation‘)
>>>
"""
class MySQLOrmTest(object):
def __init__(self):
self.session = Session()
def add_one(self):
""" 新增一条记录 """
new_obj = News(
title = ‘标题‘,
content = ‘内容‘,
types = ‘百家‘,
)
new_obj2 = News(
title = ‘title ‘,
content = ‘content ‘,
types = ‘1‘,
)
self.session.add(new_obj)
self.session.add(new_obj2)
self.session.commit()
return new_obj
def get_one(self):
""" 获取一条数据 """
return self.session.query(News).get(13) # 查询id为1的数据
def get_more(self):
""" 获取多条数据 """
return self.session.query(News).filter_by(is_valid = True) # 查询没有删除的 即 is_valid =1
def update_data(self, pk):
""" 修改单条数据 """
new_obj = self.session.query(News).get(pk)
if new_obj:
new_obj.is_valid = 0
self.session.add(new_obj)
self.session.commit()
return True
return False # 如果有数据就修改数据返回True,没有数据就直接返回False
def update_data_more(self):
""" 修改多条数据 """
#data_list = self.session.query(News).filter_by(is_valid = False)
data_list = self.session.query(News).filter(News.id >= 5)
for item in data_list:
item.is_valid = 1
self.session.add(item)
self.session.commit()
pass
def delete_data(self, pk):
""" 删除单条数据 """
# 获取删除的数据
new_obj = self.session.query(News).get(pk)
self.session.delete(new_obj)
self.session.commit()
def delete_data_more(self):
""" 删除多条数据 """
data_list = self.session.query(News).filter(News.id >= 5)
for item in data_list:
self.session.delete(item)
self.session.commit()
pass
def main():
obj = MySQLOrmTest()
# 测试插入一条数据
# rest = obj.add_one()
# print rest.id
# 测试获取一条数据
# rest = obj.get_one()
# if rest:
# print ‘ID:{0} => {1}‘.format(rest.id, rest.title) # 采用format的方式格式化
# else:
# print "No exist."
# 测试获取多条数据
# rest = obj.get_more()
# print rest.count() # 答应查询的数据条数
# for new_obj in rest:
# print ‘ID:{0} => {1}‘.format(new_obj.id, new_obj.title)
# pass
# 测试修改数据代码
# print obj.update_data(10)
# # 测试多条数据修改代码
# obj.update_data_more()
# 测试删除数据代码
# obj.delete_data(1)
# 测试删除多条数据代码
obj.delete_data_more()
if __name__ == ‘__main__‘:
main()
"""
将每一条记录看成一个对象,ORM就是把数据库的记录转换为对象。
ORM的实现:
1.SqlObject
2.peewee
3.Django‘s ORM Django框架
4.SQLAlchemy
"""
标签:将不 解释 hang ret current pack 语句 http 成功
原文地址:https://www.cnblogs.com/JCcodeblgos/p/10331542.html