python如何操作mysql

作者:云雀叫了一整天 时间:2024-01-16 23:27:28 

mysql 使用

启动服务

sudo systemctl start mysql
pip3 install pymysql

python 操作数据库:

  • 定义类


import pymysql

class MyDb():
 def __init__(self, host, user, passwd, db):
     self.__db = pymysql.connect(host, user, passwd, db)
     self.__cursor = self.__db.cursor()

# 增删改-数据库
 def set(self, sql):
   try:
     self.__cursor.execute(sql)
     self.__db.commit()
   except Exception as e:
     self.__db.rollback()
     print('Execute Error: \n {e}')

# 查-数据库
 def get(self, sql, fetchone=True):
   self.__cursor.execute(sql)
   try:
     if fetchone == True:
       data = self.__cursor.fetchone()
     else:
       data = self.__cursor.fetchall()
   except Exception as e:
     print('Execute Error: \n {e}')
     data = None
   finally:
     return data

# 关闭数据库
 def close(self):
   self.__db.close()
  • 调用


def example():
 ## 实例化数据库
 ### 类参数:host、user、passwd、db
 db = MyDb('localhost', 'root', 'zuoy123', 'test')

## 查看版本
 get_version_sql = 'SELECT VERSION()'
 version = db.get(get_version_sql)
 print(f'Database Version: {version}')

## 删除表
 delete_table_sql = 'DROP TABLE IF EXISTS employee'
 db.set(delete_table_sql)

## 新建表
 new_table_sql = 'CREATE TABLE IF NOT EXISTS employee( \
   id INT NOT NULL PRIMARY KEY, \
   name CHAR(21) NOT NULL, \
   age DOUBLE DEFAULT 18)'
 db.set(new_table_sql)

## 查找表
 get_table_sql = 'SHOW TABLES'
 data = db.get(get_table_sql)
 if data:
   print(data)

## 关闭数据库
 db.close()

if __name__ == '__main__':
 example()

常用sql


DROP TABLE IF EXISTS employee;
CREATE TABLE IF NOT EXISTS employee(id INT);

来源:https://cloud.tencent.com/developer/article/1526845

标签:python,MySQL
0
投稿

猜你喜欢

  • python实现简单温度转换的方法

    2021-04-12 10:14:51
  • Python打印特殊符号及对应编码解析

    2023-08-16 02:14:07
  • 整理及优化CSS代码的七个原则[译]

    2009-04-23 12:35:00
  • Warning: require(): open_basedir restriction in effect,目录配置open_basedir报错问题分析

    2023-06-02 23:28:18
  • 让ASP也支持动态include文件

    2008-05-08 13:00:00
  • python利用正则表达式提取字符串

    2021-12-08 15:13:29
  • 一小时学会TensorFlow2之基本操作1实例代码

    2023-03-01 23:58:10
  • accept-charset与Header P3P

    2009-04-01 18:43:00
  • Python中使用语句导入模块或包的机制研究

    2023-02-21 15:06:40
  • Python return语句如何实现结果返回调用

    2021-06-06 21:13:51
  • 快速掌握 Mysql数据库对文件操作的封装

    2009-02-23 17:37:00
  • Python yield 使用方法浅析

    2023-03-30 11:15:18
  • Python类属性与实例属性用法分析

    2022-10-12 03:14:58
  • Sql Server 2005读取外部数据的方法

    2008-07-08 19:08:00
  • Python基础之高级变量类型实例详解

    2021-11-09 11:07:40
  • 轻松搞定IE的CSS制作网页技巧3则

    2009-08-14 20:32:00
  • Python 记录日志的灵活性和可配置性介绍

    2022-06-05 12:30:15
  • mysql 8.0.21 安装配置方法图文教程

    2024-01-18 20:34:44
  • python中while循环语句用法简单实例

    2021-12-03 22:34:44
  • [xhtml+css实例]不规则导航的制作

    2008-04-04 18:11:00
  • asp之家 网络编程 m.aspxhome.com