python 使用 mysqldb类库操作数据库

1.安装MySQLdb
pip install MySQLdb

2.代码
  1. import MySQLdb

  2. class MysqlSearch(object):

  3.     def __init__(self):
  4.         self.get_conn()

  5.     def get_conn(self):
  6.         try:
  7.             self.conn = MySQLdb.connect(
  8.                 host='127.0.0.1',
  9.                 user='root',
  10.                 passwd='root',
  11.                 db='test',
  12.                 port=3308,
  13.                 charset='utf8'
  14.             )
  15.         except MySQLdb.Error as e:
  16.             print('Error: %s' % e)

  17.     def close_conn(self):
  18.         try:
  19.             if self.conn:
  20.                 # 关闭链接
  21.                 self.conn.close()
  22.         except MySQLdb.Error as e:
  23.             print('Error: %s' % e)

  24.     def get_one(self):
  25.         # 准备SQL
  26.         sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;'
  27.         # 找到cursor
  28.         cursor = self.conn.cursor()
  29.         # 执行SQL
  30.         cursor.execute(sql, ('百家', ))
  31.         # print(dir(cursor))
  32.         # 拿到结果
  33.         rest = dict(zip([k[0] for k in cursor.description], cursor.fetchone()))
  34.         # 处理数据
  35.         # 关闭cursor/链接
  36.         cursor.close()
  37.         self.close_conn()
  38.         return rest

  39.     def get_more(self):
  40.         # 准备SQL
  41.         sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC;'
  42.         # 找到cursor
  43.         cursor = self.conn.cursor()
  44.         # 执行SQL
  45.         cursor.execute(sql, ('百家', ))
  46.         # print(dir(cursor))
  47.         # 拿到结果
  48.         rest = [dict(zip([k[0] for k in cursor.description], row))
  49.             for row in cursor.fetchall()]
  50.         # 处理数据
  51.         # 关闭cursor/链接
  52.         cursor.close()
  53.         self.close_conn()
  54.         return rest

  55.     def get_more_by_page(self, page, page_size):
  56.         ''' 分页查询数据 '''
  57.         offset = (page - 1) * page_size
  58.         # 准备SQL
  59.         sql = 'SELECT * FROM `news` WHERE `types` = %s ORDER BY `created_at` DESC LIMIT %s, %s;'
  60.         # 找到cursor
  61.         cursor = self.conn.cursor()
  62.         # 执行SQL
  63.         cursor.execute(sql, ('百家', offset, page_size))
  64.         # print(dir(cursor))
  65.         # 拿到结果
  66.         rest = [dict(zip([k[0] for k in cursor.description], row))
  67.             for row in cursor.fetchall()]
  68.         # 处理数据
  69.         # 关闭cursor/链接
  70.         cursor.close()
  71.         self.close_conn()
  72.         return rest

  73.     def add_one(self):
  74.         ''' 插入数据 '''
  75.         # 受影响的行数
  76.         row_count = 0
  77.         try:
  78.             # 准备SQL
  79.             sql = (
  80.                 "INSERT INTO `news`(`title`,`image`, `content`, `types`, `is_valid`) VALUE"
  81.                 "(%s, %s, %s, %s, %s);"
  82.             )
  83.             # 获取链接和cursor
  84.             cursor = self.conn.cursor()
  85.             # 执行sql
  86.             # 提交数据到数据库
  87.             cursor.execute(sql, ('标题11', '/static/img/news/01.png', '新闻内容5', '推荐', 1))
  88.             # cursor.execute(sql, ('标题12', '/static/img/news/01.png', '新闻内容6', '推荐', 1))
  89.             # 提交事务
  90.             self.conn.commit()
  91.         except :
  92.             print('error')
  93.             # 回滚事务
  94.             self.conn.rollback()
  95.         # 执行最后一条SQL影响的行数
  96.         row_count = cursor.rowcount
  97.         # 关闭cursor和链接
  98.         cursor.close()
  99.         self.close_conn()
  100.         # row_count > 0 表示成功
  101.         return row_count > 0



  102. def main():
  103.     obj = MysqlSearch()
  104.     # rest = obj.get_one()
  105.     # print(rest['title'])

  106.     # rest = obj.get_more()
  107.     # for item in rest:
  108.     # print(item)
  109.     # print('------')

  110.     # rest = obj.get_more_by_page(2, 3)
  111.     # for item in rest:
  112.     # print(item)
  113.     # print('------')

  114.     rest = obj.add_one()
  115.     print(rest)


  116. if __name__ == '__main__':
  117.     main()

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/30523439/viewspace-2156930/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/30523439/viewspace-2156930/

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值