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()
    原文作者:天下无敌庞成勇
    原文地址: http://blog.itpub.net/30523439/viewspace-2156930/
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞