MySQLdb exemplary operation flow database with:

Copy and paste the following content directly into the sublime, the ****** py saved as a file and then run it in a python environment;

 

'' 'MySQLdb operation itself is a widget python mysql database, MySQLdb python achieved by additions and deletions to the database change search' ''
Import MySQLdb

class MysqlSearch(object):
def __init__(self):
self.get_conn()

'''获取连接'''
def get_conn(self):
try:
self.conn = MySQLdb.connect(
host='rm-wz9lp7a734h99y0s5yo.mysql.rds.aliyuncs.com',
user='hiadmin',
passwd='1q2w3e$R',
db='news',
port=3306,
charset='utf8',
)
except MySQLdb.Error as e:
print('Error:%s' %e)
'''关闭连接,为了节省资源'''
def close_conn(self):
try:
if self.conn:
self.conn.close()
except MySQLdb.Error as e:
print('Error: %s' %e)

'''获取一条数据'''
def get_one(self):
#准备SQL
sql = 'SELECT * FROM `news` WHERE `types`=%s ORDER BY `created_at` DESC;'
#找到cursor
cursor = self.conn.cursor()
#执行sql
cursor.execute(sql,('types2',))
#拿到结果
rest = cursor.fetchone()
#处理数据
print(rest)
#关闭cursor/连接
cursor.close()
self.close_conn()

'''获取多条数据'''
def get_more(self,page,page_size):
offset = (page_size-1)*page_size
#准备SQL
sql = 'SELECT * FROM `news` WHERE `types`=%s ORDER BY `created_at` DESC %s %s;'
#找到cursor
cursor = self.conn.cursor()
#执行sql
cursor.execute(sql,('types2',))
#拿到结果
rest = [dict(zip([k[0] for k in cursor.description], row)) for row in cursor.fetchall()]
#处理数据
print(rest)
#关闭cursor/连接
cursor.close()
self.close_conn()

'''增加一条数据'''
def add_one(self):
try:
sql = ("INSERT INTO `news` (`title`,`image`,`content`,`types`,`is_valide`) VALUE"
"(%s,%s,%s,%s,%s);")
cursor = self.conn.cursor()
cursor.execute(sql,('新闻标题5','图片2','新闻内容4','推荐',1))
cursor.execute(sql,('新闻标题6','图片3','新闻内容5','推荐',1,0))
self.conn.commit()
cursor.close()
self.close_conn()
except:
print('error')
self.conn.roolback()

'''主函数入口'''
def main():
obj = MysqlSearch()
# obj.get_more()
obj.add_one()

if __name__ == '__main__':
main()


'''
---ReadMe---
用MySQLdb操作数据库流程示例:
导入插件,建立连接,增删改查,关闭连接,运行主函数;

'''

Guess you like

Origin www.cnblogs.com/braveheart007/p/11022591.html