import MySQLdb
class 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='',
db='news',
port=3308,
charset='utf8'
)
except MySQLdb.Error as e:
print('Error: %s' % e)
def close_conn(self):
try:
if self.conn:
# 關(guān)閉鏈接
self.conn.close()
except MySQLdb.Error as e:
print('Error: %s' % e)
def get_one(self):
# 準(zhǔn)備SQL
sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;'
# 找到cursor
cursor = self.conn.cursor()
# 執(zhí)行SQL
cursor.execute(sql, ('百家', ))
# print(dir(cursor))
# 拿到結(jié)果
rest = dict(zip([k[0] for k in cursor.description], cursor.fetchone()))
# 處理數(shù)據(jù)
# 關(guān)閉cursor/鏈接
cursor.close()
self.close_conn()
return rest
def get_more(self):
# 準(zhǔn)備SQL
sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;'
# 找到cursor
cursor = self.conn.cursor()
# 執(zhí)行SQL
cursor.execute(sql, ('百家', ))
# print(dir(cursor))
# 拿到結(jié)果
rest = [dict(zip([k[0] for k in cursor.description], row))
for row in cursor.fetchall()]
# 處理數(shù)據(jù)
# 關(guān)閉cursor/鏈接
cursor.close()
self.close_conn()
return rest
def get_more_by_page(self, page, page_size):
''' 分頁(yè)查詢數(shù)據(jù) '''
offset = (page - 1) * page_size
# 準(zhǔn)備SQL
sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC LIMIT %s, %s;'
# 找到cursor
cursor = self.conn.cursor()
# 執(zhí)行SQL
cursor.execute(sql, ('百家', offset, page_size))
# print(dir(cursor))
# 拿到結(jié)果
rest = [dict(zip([k[0] for k in cursor.description], row))
for row in cursor.fetchall()]
# 處理數(shù)據(jù)
# 關(guān)閉cursor/鏈接
cursor.close()
self.close_conn()
return rest
def add_one(self):
''' 插入數(shù)據(jù) '''
# 受影響的行數(shù)
row_count = 0
try:
# 準(zhǔn)備SQL
sql = (
"INSERT INTO `news`(`title`,`image`, `content`, `types`, `is_valid`) VALUE"
"(%s, %s, %s, %s, %s);"
)
# 獲取鏈接和cursor
cursor = self.conn.cursor()
# 執(zhí)行sql
# 提交數(shù)據(jù)到數(shù)據(jù)庫(kù)
cursor.execute(sql, ('標(biāo)題11', '/static/img/news/01.png', '新聞內(nèi)容5', '推薦', 1))
# cursor.execute(sql, ('標(biāo)題12', '/static/img/news/01.png', '新聞內(nèi)容6', '推薦', 1))
# 提交事務(wù)
self.conn.commit()
except :
print('error')
# 回滾事務(wù)
self.conn.rollback()
# 執(zhí)行最后一條SQL影響的行數(shù)
row_count = cursor.rowcount
# 關(guān)閉cursor和鏈接
cursor.close()
self.close_conn()
# row_count > 0 表示成功
return row_count > 0
def main():
obj = MysqlSearch()
# rest = obj.get_one()
# print(rest['title'])
# rest = obj.get_more()
# for item in rest:
#? ? print(item)
#? ? print('------')
# rest = obj.get_more_by_page(2, 3)
# for item in rest:
#? ? print(item)
#? ? print('------')
rest = obj.add_one()
print(rest)
if __name__ == '__main__':
main()