数据存储之关系型数据库存储---MySQL存储

MySQL的存储

  • 利用PyMySQL连接MySQL

    • 连接数据库

      import pymysql
      
      # 连接MySQL           MySQL在本地运行      用户名为root         密码为123456    默认端口3306
      db = pymysql.connect(host='localhost', user='root', password='123456', port=3306)
      
      # cursor()方法获得MySQL的操作游标,利用游标来执行SQL语句,其中执行方法为execute()
      cursor = db.cursor()
      
      # 获取MySQL的当前版本
      cursor.execute('SELECT VERSION()')
      
      # fetchone()方法获得第一条数据,即版本号
      data = cursor.fetchone()
      print('Database version:', data)
      
      # 创建一个名为reptile的数据库,默认编码为utf8mb4
      cursor.execute("CREATE DATABASE reptile DEFAULT CHARACTER SET utf8mb4")
      db.close()
      
      
      
      # 运行输出:
      Database version: ('8.0.16',)
      # 运行生成一个名为reptile的数据库
      View Code

       

    • 创建表

      import pymysql
      
      db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile')
      cursor = db.cursor()
      sql = '''CREATE TABLE
            IF NOT EXISTS students
            (
            id VARCHAR(255) NOT NULL,
            name VARCHAR(255) NOT NULL,
            age INT NOT NULL,
            PRIMARY KEY (id)
            )'''
      # 创建一个名为students的数据表,主键为id
      cursor.execute(sql)
      db.close()
      
      # 运行创建一个数据表
      View Code

       

    • 插入数据

      import pymysql
      
      id = '20180001'
      user = 'Lee Hua'
      age = 20
      
      # 连接数据库
      db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile')
      # 获得MySQL的操作游标
      cursor = db.cursor()
      sql = '''INSERT INTO students(id, name, age) VALUES(%s %s %s)'''
      
      try:
          # 执行
          cursor.execute(sql, (id, user, age))
          # 数据插入、更新、删除操作,都需要用到commit()方法才能生效
          db.commit()
      
      except:
          # 调用rollback()执行数据回滚,相当于什么都没有发生过
          db.rollback()
      
      db.close()
      
      
      # 运行,数据被插入到数据表中
      View Code
      import pymysql
      
      db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile')
      cursor = db.cursor()
      
      
      data = {
          'id': '20180002',
          'user': 'Lao wang',
          'age': 19
      }
      table_name = 'students'
      keys = ', '.join(data.keys())                   # id, user, age
      values = ', '.join(['%s'] * len(data))          # ['%s', '%s', ......]   len(data)个'%s'
      sql = '''INSERT INTO {table_name}({keys}) VALUES({values})'''.format(table_name=table_name, keys=keys, values=values)
      # sql = INSERT INTO students(id, name, age) VALUES(%s %s %s)
      
      
      try:
          tuple_ = tuple(data.values())
          if cursor.execute(sql, tuple_):
              print('成功插入数据')
          db.commit()
      
      except:
          print('插入数据失败')
          db.rollback()
      
      db.close()
      
      # 与上面一个例子做比较
      View Code

       

    • 更新数据

      import pymysql
      
      db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile')
      cursor = db.cursor()
      
      sql = 'UPDATA students SET age = %s WHERE name = %s'
      try:
          cursor.execute(sql, (25, 'Bob'))
          db.commit()
      except:
          db.rollback()
      
      db.close()
      
      简单方式数据更新
      简单方式数据更新
      # 实现去重(如果数据存在,则更新数据;如果数据不存在,则插入数据。)
      import pymysql
      
      db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile')
      cursor = db.cursor()
      
      
      data = {
          'id': '20180002',
          'user': 'Lao wang',
          'age': 19
      }
      table_name = 'students'
      keys = ', '.join(data.keys())                               # keys = id, name, age
      values = ', '.join(['%s'] * len(data))                      # values = %s, %s, %s
      update = ', '.join(
          [" {key} = %s".format(key=key) for key in data]
      )                                                           # id = %s, name = %s, age = %s
      sql = '''INSERT INTO {table_name}({keys}) VALUES({values}) ON DUPLICATE KEY update'''.format(table_name=table_name, keys=keys, values=values)
      # ON DUPLICATE KEY UPDATE 表示:如果主键已经存在,那么就执行更新操作
      
      try:
          tuple_ = tuple(data.values())
          if cursor.execute(sql, tuple_):
              print('成功插入数据')
          db.commit()
      
      except:
          print('插入数据失败')
          db.rollback()
      
      db.close()
      View Code

       

    • 删除数据

      import pymysql
      
      db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile')
      cursor = db.cursor()
      
      table = 'students'
      condition = 'age > 20'
      sql = 'DELETE FROM {table} WHERE {conditon}'.format(table=table, conditon=condition)
      try:
          cursor.execute(sql)
          db.commit()
      except:
          db.rollback()
      
      db.close()
      
      
      # 删除age > 20的数据
      简单示例

       

    • 查询数据

      import pymysql
      
      db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile')
      cursor = db.cursor()
      
      sql = 'SELECT * FROM students WHERE age >= 20'
      try:
          cursor.execute(sql)
          print('Count:', cursor.rowcount)        # 调用cursor的rowcount属性,获取查询结果的条数
          one = cursor.fetchone()                 # 获取结果的第一条信息
          print('One:', one)
          result = cursor.fetchall()              # 获取结果的所有数据
          print('Result:', result)
          print('Result Type:', type(result))
          for row in result:
              print(row)
      except:
          print('Error')
      
      
      # 输出:
      Count: 0
      One: None
      Result: ()
      Result Type: <class 'tuple'>
      一次性查询所有数据----fetchall()
      import pymysql
      
      db = pymysql.connect(host='localhost', user='用户名', password='密码', port=3306, db='reptile')
      cursor = db.cursor()
      
      sql = 'SELECT * FROM students WHERE age >= 20'
      try:
          cursor.execute(sql)
          print('Count:', cursor.rowcount)        # 调用cursor的rowcount属性,获取查询结果的条数
          row = cursor.fetchone()                 # 获取结果的第一条数据
          while row:
              print('Row:', row)
              row = cursor.fetchone()
      except:
          print('Error')
      逐条查询数据----fatchone()



转载于:https://www.cnblogs.com/liyihua/p/11178496.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值