当前位置:   article > 正文

【数据库学习】——Python实现mysql数据库SQL文件生成和导入_python 导出mysql数据

python 导出mysql数据

目录

1、将mysql数据导出到SQL文件中(数据库存在的情况)

2、将现有的sql文件数据导入到数据库中(前提数据库存在) 

 3、利用Navicat导出SQL文件和导入SQL文件

1)从数据库导出SQL文件

2)导入SQL文件到数据库 


1、将mysql数据导出到SQL文件中(数据库存在的情况)

主要需要修改数据库的相关信息,端口号、用户名、密码等

其中数据库得存在,不然会报错 

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @Time : 2022/5/29 13:06
  4. # @Author : @linlianqin
  5. # @Site :
  6. # @File : exportSqlFile.py
  7. # @Software: PyCharm
  8. # @description:导出数据库文件sql
  9. import os
  10. class InitSql(object):
  11. sql_file = "A.sql"
  12. def import_server_db(self):
  13. mysqldump_commad_dict = {'dumpcommad': 'mysqldump ', 'server': 'localhost', 'user': 'root',
  14. 'password': 'root', 'port': 3306, 'db': 'studentmanagersystem'}
  15. # mysqldump 命令
  16. sqlfromat = "mysqldump --column-statistics=0 -h%s -u%s -p%s -P%s %s > %s"
  17. # 生成相应的sql语句
  18. sql = (sqlfromat % (mysqldump_commad_dict['server'],
  19. mysqldump_commad_dict['user'],
  20. mysqldump_commad_dict['password'],
  21. mysqldump_commad_dict['port'],
  22. mysqldump_commad_dict['db'],
  23. self.sql_file))
  24. print("执行的导出数据库的sql:" + sql)
  25. result = os.system(sql)
  26. return result
  27. if __name__ == '__main__':
  28. initSql = InitSql()
  29. initSql.import_server_db()
'
运行

生成的sql文件如下所示:

-- MySQL dump 10.13  Distrib 8.0.29, for Win64 (x86_64)
--
-- Host: localhost    Database: studentmanagersystem
-- ------------------------------------------------------
-- Server version  8.0.29

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `studenttable`
--

DROP TABLE IF EXISTS `studenttable`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `studenttable` (
  `number` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `sex` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `classes` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `floor` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `room` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `tel` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `money` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  PRIMARY KEY (`number`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `studenttable`
--

LOCK TABLES `studenttable` WRITE;
/*!40000 ALTER TABLE `studenttable` DISABLE KEYS */;
INSERT INTO `studenttable` VALUES ('2201','刘同学','男','1班','A1','101','1112','30'),('2202','张同学','男','2班','A2','211','1121','13'),('2203','管同学','女','2班','A3','121','1122','11'),('2204','管同学','女','2班','A3','121','1122','11'),('2205','刘同学','女','2班','A3','121','1122','11'),('2206','张同学','男','2班','A2','211','1121','13'),('2208','杨同学','男','1班','A1','101','1112','30'),('2209','蔡同学','男','1班','A1','101','1112','30');
/*!40000 ALTER TABLE `studenttable` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2022-06-05  0:30:03

2、将现有的sql文件数据导入到数据库中(前提数据库存在) 

这里的话其实就是将SQL文件进行分割成一条条SQL语句,然后顺序执行即可

  1. import pymysql
  2. from pathlib import Path
  3. class ConnectMsql:
  4. def __init__(self, host='localhost', port=3306, user='root',
  5. password='root', database="studentmanagersystem", filename: str = "studenttable.sql"):
  6. """
  7. :param host: 域名
  8. :param port: 端口
  9. :param user: 用户名
  10. :param password: 密码
  11. :param database: 数据库名
  12. :param filename: 文件名称
  13. """
  14. self._host: str = host
  15. self._port: int = port
  16. self._user: str = user
  17. self._password: str = password
  18. self._database: str = database
  19. self._file_path = Path(__file__).parent.joinpath(filename)
  20. def _show_databases_and_create(self):
  21. """
  22. 查询数据库是否存在,不存在则进行新建操作
  23. :return:
  24. """
  25. connection = pymysql.connect(host=self._host, port=self._port, user=self._user, password=self._password,
  26. cursorclass=pymysql.cursors.DictCursor)
  27. with connection:
  28. with connection.cursor() as cursor:
  29. cursor.execute('show databases;')
  30. result = cursor.fetchall()
  31. results = self._database not in tuple(x["Database"] for x in result)
  32. if results:
  33. with connection.cursor() as cursor:
  34. cursor.execute(f'create database {self._database};')
  35. with connection.cursor() as cursor:
  36. cursor.execute('show databases;')
  37. result = cursor.fetchall()
  38. results = self._database in tuple(x["Database"] for x in result)
  39. return results if results else result
  40. else:
  41. return True
  42. def _export_databases_data(self):
  43. """
  44. 读取.sql文件,解析处理后,执行sql语句
  45. :return:
  46. """
  47. if self._show_databases_and_create() is True:
  48. connection = pymysql.connect(host=self._host, port=self._port, user=self._user, password=self._password,
  49. database=self._database, charset='utf8')
  50. # 读取sql文件,并提取出sql语句
  51. results, results_list = "", []
  52. with open(self._file_path, mode="r+", encoding="utf-8") as r:
  53. for sql in r.readlines():
  54. # 去除数据中的“\n”和“\r”字符
  55. sql = sql.replace("\n", "").replace("\r", "")
  56. # 获取不是“--”开头且不是“--”结束的数据
  57. if not sql.startswith("--") and not sql.endswith("--"):
  58. # 获取不是“--”的数据
  59. if not sql.startswith("--"):
  60. results = results + sql
  61. # 根据“;”分割数据,处理后插入列表中
  62. for i in results.split(";"):
  63. if i.startswith("/*"):
  64. results_list.append(i.split("*/")[1] + ";")
  65. # print(i.split("*/")[1] + ";")
  66. else:
  67. results_list.append(i + ";")
  68. # print(i + ";")
  69. # 执行sql语句
  70. with connection:
  71. with connection.cursor() as cursor:
  72. # 循环获取sql语句
  73. for x in results_list[:-1]:
  74. if x != ";":
  75. print(x)
  76. # 执行sql语句
  77. cursor.execute(x)
  78. # 提交事务
  79. connection.commit()
  80. else:
  81. return "sql全部语句执行成功 !"
  82. @property
  83. def sql_run(self):
  84. """
  85. 执行方法
  86. :return:
  87. """
  88. return self._export_databases_data()
  89. if __name__ == '__main__':
  90. res = ConnectMsql().sql_run
  91. print(res)

 利用Navicat软件可视化数据库,可以看到导入SQL文件成功

 3、利用Navicat导出SQL文件和导入SQL文件

1)从数据库导出SQL文件

选择需要导出的数据表——右键——转储为SQL文件——数据和结构

这样就可以将数据表的结构和数据都一起保存在SQL文件中

2)导入SQL文件到数据库 

右键选中需要导入的数据库——运行SQL文件

 点击开始后,即开始运行SQL文件,出现下述字样表明导入SQL文件成功

 

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/967451
推荐阅读
相关标签
  

闽ICP备14008679号