python中怎么利用 mysqldb类库操作数据库

发布时间:2021-07-05 18:29:26 作者:Leah
来源:亿速云 阅读:131

这期内容当中小编将会给大家带来有关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()

上述就是小编为大家分享的python中怎么利用 mysqldb类库操作数据库了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. Python是怎么样操作mysql数据库的
  2. python中conn指的是什么意思

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mysqldb python

上一篇:CMD常用运行指令有哪些

下一篇:怎么在 DOS 下驱动光驱

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》