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 ...
随机推荐
- HDU 1021(斐波那契数与因子3 **)
题意是说在给定的一种满足每一项等于前两项之和的数列中,判断第 n 项的数字是否为 3 的倍数. 斐波那契数在到第四十多位的时候就会超出 int 存储范围,但是题目问的是是否为 3 的倍数,也就是模 3 ...
- Python复习笔记(六)网络编程(udp/tcp)
一.网络-udp(用户数据报协议) 用户数据报协议 类似写信,不安全,数据有可能丢 1.1 ip地址 注意: IP地址127.0.0.1 ~ 127.255.255.255 用于回路测试 私有ip地址 ...
- bash 刷题leetcode
题目一: 给定一个文本文件 file.txt,请只打印这个文件中的第十行. 示例: 假设 file.txt 有如下内容: Line 1 Line 2 Line 3 Line 4 Line 5 Line ...
- vue-router路由
Vue Router 是 Vue.js 官方的路由管理器 自动全局安装: vue create 项目名称 手动配置: 1.安装 在app项目文件夹里面 npm i vue-router 2.在min. ...
- SpringBoot入门笔记(一)、HelloWorld
本文是一篇SprintBoot学习入门笔记 1.打开Eclipse,版本为Oxygen 4.7.0 2.新建项目NewProject->MavenProject->Next->Nex ...
- Windows 操作系统
Microsoft Windows,是美国微软公司研发的一套操作系统,它问世于1985年,起初仅仅是Microsoft-DOS模拟环境,后续的系统版本由于微软不断的更新升级,不但易用,也慢慢的成为家家 ...
- pycharm使用方法
https://blog.csdn.net/zhaihaifei/article/details/51658425
- MVC下 Area和Web同名的Controller问题
错误如下图: 解决方案: 1:Area下的XXXAreaRegistration 添加:new string[] { "xxx.Areas.xxx.Controllers" } 2 ...
- sum() over (order by )
sum(x) over( partition by y ORDER BY z ) 分析 sum(x) over (partition by y order by z) 求安照y分区,然后按z排序,连续 ...
- oracle 利用over 查询数据和总条数,一条sql搞定
select count(*) over()总条数 ,a.*from table a