python操作三大主流数据库(2)python操作mysql②python对mysql进行简单的增删改查
python操作mysql②python对mysql进行简单的增删改查 1.设计mysql的数据库和表 id:新闻的唯一标示
title:新闻的标题
content:新闻的内容
created_at:新闻添加的时间
types:新闻的类型
image:新的缩略图
author:作者
view_count:浏览量
is_valid:删除标记 # 创建新闻数据库
create database news charset=utf8; # 创建新闻表
create table news(
id int primary key auto_increment,
title varchar(200) not null,
content varchar(2000) not null,
types varchar(10) not null,
image varchar(300) null,
author varchar(20) null,
view_count int default 0,
created_at datetime null,
is_valid smallint default 1
) default charset="utf8";
''' 插入数据
INSERT INTO `news` VALUES ('1', '朝鲜特种部队视频公布 展示士兵身体素质与意志', '新闻内容', '推荐', '/static/img/news/01.png', null, '0', null, '1');
INSERT INTO `news` VALUES ('2', '男子长得像\"祁同伟\"挨打 打人者:为何加害检察官', '新闻内容', '百家', '/static/img/news/02.png', null, '0', null, '1');
INSERT INTO `news` VALUES ('3', '导弹来袭怎么办?日本政府呼吁国民堕入地下通道', '新闻内容', '本地', '/static/img/news/03.png', null, '0', null, '1');
INSERT INTO `news` VALUES ('4', '美监:朝在建能发射3发以上导弹的3000吨级新潜艇', '新闻内容', '推荐', '/static/img/news/04.png', null, '0', null, '1');
INSERT INTO `news` VALUES ('5', '证监会:前发审委员冯小树违法买卖股票被罚4.99亿', '新闻内容', '百家', '/static/img/news/08.png', null, '0', null, '1');
INSERT INTO `news` VALUES ('6', '外交部回应安倍参拜靖国神社:同军国主义划清界限', '新闻内容', '推荐', '/static/img/news/new1.jpg', null, '0', null, '1');
INSERT INTO `news` VALUES ('7', '\"萨德\"供地违法?韩民众联名起诉要求撤回供地', '新闻内容', '百家', '/static/img/news/new2.jpg', null, '0', null, '1');
INSERT INTO `news` VALUES ('10', '标题1', '新闻内容1', '推荐', '/static/img/news/01.png', null, '0', null, '1'); 2.python简单操作mysql之数据库的连接和简单获取数据
#encoding:utf-8 import MySQLdb '''
# 简单的连接
# 获取连接
conn = MySQLdb.connect(
host = '127.0.0.1',
user = 'root',
password = '',
db = 'news',
port = 3306,
charset = 'utf8'
) # 获取数据
cursor = conn.cursor()
cursor.execute('select * from news order by created_at desc')
rest = cursor.fetchone()
print(rest) # 关闭连接
conn.close() 3.python简单操作mysql之数据库的连接和简单获取数据改进之捕获异常 # 捕获异常
# 获取连接
try:
conn = MySQLdb.connect(
host = '127.0.0.1x',
user = 'root',
password = '',
db = 'news',
port = 3306,
charset = 'utf8'
) # 获取数据
cursor = conn.cursor()
cursor.execute('select * from news order by created_at desc')
rest = cursor.fetchone()
print(rest) # 关闭连接
conn.close()
except MySQLdb.Error as e:
print('mysql error:%s' % e) 4.python简单操作mysql之数据库的连接和单获取所有数据
# 获取连接
try:
conn = MySQLdb.connect(
host = '127.0.0.1',
user = 'root',
password = '',
db = 'news',
port = 3306,
charset = 'utf8'
) # 获取数据
cursor = conn.cursor()
cursor.execute('select * from news')
rows = cursor.fetchall()
print(cursor.description) for row in rows:
print(row) # 关闭连接
conn.close()
except MySQLdb.Error as e:
print('mysql error:%s' % e) 5.python简单操作mysql之数据库的操作类 class MysqlConnection(object): # 初始化
def __init__(self, host = '127.0.0.1', port = 3306, user = 'root', password = '', db = 'news',charset='utf8'):
self._host = host
self._port = port
self._user = user
self._password = password
self._db = db
self._charset = charset
self._conn = None
self._cursor = None
self.get_conn() # 关闭数据库连接
def close(self):
if self._cursor:
self._cursor.close()
self._cursor = None if self._conn:
self._conn.close()
self._conn = None def commit(self):
self._conn.commit() # 获取数据库连接
def get_conn(self):
try:
self._conn = MySQLdb.connect(
host = self._host,
user = self._user,
password = self._password,
db = self._db,
port = self._port,
charset = self._charset
) self._cursor = self._conn.cursor()
except MySQLdb.Error as e:
print('mysql error:%s' % e) # 获取单条新闻
def get_one(self): sql = 'select * from news where types = %s order by created_at desc'
# 获取数据
self._cursor.execute(sql,('百家',))
rest = dict(zip([k[0] for k in self._cursor.description], self._cursor.fetchone())) # 关闭连接
self.close()
return rest # 获取多条新闻
def get_more(self): sql = 'select * from news where types = %s order by created_at desc'
# 获取数据
self._cursor.execute(sql,('百家',))
rest = [dict(zip([k[0] for k in self._cursor.description], row))
for row in self._cursor.fetchall()] # 关闭连接
self.close()
return rest def add_one(self):
sql = 'insert into news(title,image,content,types,is_valid) values(%s, %s, %s, %s, %s)'
self._cursor.execute(sql, ('标题1','/static/img/news/01.png', '新闻内容1','推荐',1))
self.commit()
self.close() def main():
obj = MysqlConnection()
# rst = obj.get_more()
# rst = obj.get_one()
# print(rst)
obj.add_one() if __name__ == "__main__":
main()
python操作三大主流数据库(2)python操作mysql②python对mysql进行简单的增删改查的更多相关文章
- python操作三大主流数据库(14)python操作redis之新闻项目实战②新闻数据的展示及修改、删除操作
python操作三大主流数据库(14)python操作redis之新闻项目实战②新闻数据的展示及修改.删除操作 项目目录: ├── flask_redis_news.py ├── forms.py ├ ...
- python操作三大主流数据库(12)python操作redis的api框架redis-py简单使用
python操作三大主流数据库(12)python操作redis的api框架redis-py简单使用 redispy安装安装及简单使用:https://github.com/andymccurdy/r ...
- Python操作三大主流数据库☝☝☝
Python操作三大主流数据库☝☝☝ Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数 ...
- Python操作三大主流数据库✍✍✍
Python操作三大主流数据库 Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数据库, ...
- python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作
1.通过 pip 安装 pymysql 进入 cmd 输入 pip install pymysql 回车等待安装完成: 安装完成后出现如图相关信息,表示安装成功. 2.测试连接 import ...
- C#+Access 员工信息管理--简单的增删改查操作和.ini配置文件的读写操作。
1.本程序的使用的语言是C#,数据库是Access2003.主要是对员工信息进行简单的增删改查操作和对.ini配置文件的读写操作. 2.代码运行效果如下: 功能比较简单.其中在得到查询结果后,在查询结 ...
- 使用JDBC分别利用Statement和PreparedStatement来对MySQL数据库进行简单的增删改查以及SQL注入的原理
一.MySQL数据库的下载及安装 https://www.mysql.com/ 点击DOWNLOADS,拉到页面底部,找到MySQL Community(GPL)Downloads,点击 选择下图中的 ...
- 用CI框架向数据库中实现简单的增删改查
以下代码基于CodeIgniter_2.1.3版 用PHP向数据库中实现简单的增删改查(纯代码)请戳 http://www.cnblogs.com/corvoh/p/4641476.html Code ...
- python操作三大主流数据库(8)python操作mongodb数据库②python使用pymongo操作mongodb的增删改查
python操作mongodb数据库②python使用pymongo操作mongodb的增删改查 文档http://api.mongodb.com/python/current/api/index.h ...
随机推荐
- PHP7 学习笔记(十四)Reids 键空间通知配合TP5 实现分布式延时任务
测试环境:windows 10 + phpStudy 配置redis配置文件 redis.windows.conf notify-keyspace-events "Ex" 重启re ...
- in和hasOwnProperty的区别
两者都代表查看某个属性是不是对象自己的,返回布尔值 in判断的是对象的所有属性,包括对象实例及其原型的属性 hasOwnProperty则是判断对象实例的是否具有某个属性
- java.io.OutputStream & java.io.FileOutputStream
java.io.OutputStream & java.io.FileOutputStream 1.Java.io.OutputStream(字节输出流) 字节输出流,这是一个抽象类,是表示输 ...
- 【poj1741】Tree 树的点分治
题目描述 Give a tree with n vertices,each edge has a length(positive integer less than 1001). Define dis ...
- vs 调式连接oracle报错问题32,64位问题
wind8 系统选择项目时生成目标平台选择为X86 报错“System.Exception”类型的未经处理的异常在 WindowsFormsApplication1.exe 中发生 其他信息: 尝试加 ...
- influxdb
1.安装Centos# wget https://dl.influxdata.com/influxdb/releases/influxdb-1.1.0.x86_64.rpm# rpm -ivh inf ...
- SaltStack 理解
一.SaltStack 原理: 1.SaltStack 也是基于CS模式的主控master和client被控端 minion 结构:也是一个异构平台基础设置管理工具:遵守Apache2协议,完全开源. ...
- 用Kersa搭建神经网络【MNIST手写数据集】
MNIST手写数据集的识别算得上是深度学习的”hello world“了,所以想要入门必须得掌握.新手入门可以考虑使用Keras框架达到快速实现的目的. 完整代码如下: # 1. 导入库和模块 fro ...
- jdk下载地址
1.5 http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase5 ...
- 5.28 js基础 简介
Web前端有三层: HTML:从语义的角度,描述页面结构 CSS:从审美的角度,描述样式(美化页面) JavaScript:从交互的角度,描述行为(提升用户体验) JavaScript历史背景介绍 布 ...