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进行简单的增删改查的更多相关文章

  1. python操作三大主流数据库(14)python操作redis之新闻项目实战②新闻数据的展示及修改、删除操作

    python操作三大主流数据库(14)python操作redis之新闻项目实战②新闻数据的展示及修改.删除操作 项目目录: ├── flask_redis_news.py ├── forms.py ├ ...

  2. python操作三大主流数据库(12)python操作redis的api框架redis-py简单使用

    python操作三大主流数据库(12)python操作redis的api框架redis-py简单使用 redispy安装安装及简单使用:https://github.com/andymccurdy/r ...

  3. Python操作三大主流数据库☝☝☝

    Python操作三大主流数据库☝☝☝ Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数 ...

  4. Python操作三大主流数据库✍✍✍

    Python操作三大主流数据库 Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数据库, ...

  5. python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作

    1.通过 pip 安装 pymysql 进入 cmd  输入  pip install pymysql   回车等待安装完成: 安装完成后出现如图相关信息,表示安装成功. 2.测试连接 import ...

  6. C#+Access 员工信息管理--简单的增删改查操作和.ini配置文件的读写操作。

    1.本程序的使用的语言是C#,数据库是Access2003.主要是对员工信息进行简单的增删改查操作和对.ini配置文件的读写操作. 2.代码运行效果如下: 功能比较简单.其中在得到查询结果后,在查询结 ...

  7. 使用JDBC分别利用Statement和PreparedStatement来对MySQL数据库进行简单的增删改查以及SQL注入的原理

    一.MySQL数据库的下载及安装 https://www.mysql.com/ 点击DOWNLOADS,拉到页面底部,找到MySQL Community(GPL)Downloads,点击 选择下图中的 ...

  8. 用CI框架向数据库中实现简单的增删改查

    以下代码基于CodeIgniter_2.1.3版 用PHP向数据库中实现简单的增删改查(纯代码)请戳 http://www.cnblogs.com/corvoh/p/4641476.html Code ...

  9. python操作三大主流数据库(8)python操作mongodb数据库②python使用pymongo操作mongodb的增删改查

    python操作mongodb数据库②python使用pymongo操作mongodb的增删改查 文档http://api.mongodb.com/python/current/api/index.h ...

随机推荐

  1. bzoj千题计划318:bzoj1396: 识别子串(后缀自动机 + 线段树)

    https://www.lydsy.com/JudgeOnline/problem.php?id=1396 后缀自动机的parent树上,如果不是叶子节点,那么至少有两个子节点 而一个状态所代表子串的 ...

  2. HDU 1575(裸矩阵快速幂)

    emmmmm..就是矩阵快速幂,直接附代码: #include <cstdio> using namespace std; ; ; struct Matrix { int m[maxn][ ...

  3. HTML第三耍 图像标签

    复习一下第二耍: <!doctype html> <html> <head> <meta charset="utf-8"> < ...

  4. 在 CentOS6 上安装 Zabbix3.0 Agent 并开启客户端自动注册

    #!/bin/bash # # .配置yum源 # cat /etc/redhat-release |grep -i centos |grep '6.[[:digit:]]' &>/de ...

  5. UUID在Java中的实现与应用

    UUID是什么 UUID的全称为:Universally Unique IDentifier,也被称为GUID(Globally Unique IDentifier).是一种由算法生成的唯一标识,它实 ...

  6. 学院派福利——C#+SQL Server图书管理系统

    这是sql server的第七.八次上机内容,抽了几天时间给做了 在原有的booksDB库中加了一个Admin表:UserName:root,PassWord:123456. 环境:Visual St ...

  7. javascript获取值

    <div id='name'>张三</div> $('#name').val() $(name).val() 以上两个都可以得到值,第一种用的比较多.

  8. tcp_connect函数

    #include <netdb.h> #include <stddef.h> #include <unistd.h> #include <strings.h& ...

  9. .Net core 使用特性Attribute验证Session登陆状态

    1.新建一个.net core mvc项目 2.在Models文件夹下面添加一个类MyAttribute,专门用来保存我们定义的特性 在这里我只写了CheckLoginAttribute用来验证登陆情 ...

  10. Centos7 nginx提示错误 Access denied.

    SELinux will cause this error on CentOS/RHEL 7+ by default :( CentOS/RHEL 7+ 系统默认会因为SELinux出现这个报错 To ...