forked from HH41/Back-End
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cnblogs_db.py
40 lines (34 loc) · 1.12 KB
/
cnblogs_db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# -*- codeing = utf-8 -*-
# @Time : 2021/11/13 16:09
# @Author : zhy
# @File : cnblogs_db.py
# @Software: PyCharm
import pymysql
class DataManager:
def __init__(self, db_name):
self.db = self.connect_to_db(db_name)
def connect_to_db(self, db_name):
db = pymysql.connect(host='localhost',user='root',password='密码',port=3306,db=db_name)
return db
def close_db(self):
self.db.close()
def clear_table(self):
cursor = self.db.cursor()
sql3 = 'DELETE FROM cnblogs_news'
try:
cursor.execute(sql3)
self.db.commit()
print('clear table ok')
except Exception as e:
self.db.rollback()
print('clear talbe error: ', e)
def trans_to_news_table(self, data):
cursor = self.db.cursor()
sql3 = 'INSERT INTO cnblogs_news(title, content) values(%s, %s)'
try:
cursor.execute(sql3, (data['title'], data['content']))
self.db.commit()
print('insert ok')
except Exception as e:
self.db.rollback()
print('insert error: ', e)