Ubuntu下通过python使用MySQL

news/2024/11/17 17:51:23/

参考资料

  1. MySQL Connector/Python Developer Guide

环境

  1. Ubuntu 20.04
  2. Python 3.8.10
  3. MySQL Server 8.0.34
  4. mysql-connector-python 8.1.0

安装MySQL

pip install mysql-connector-python	# 注意,不要安装成 mysql-connector 了

环境测试

注意:

  1. 千万不能命名为mysql.py!
  2. 千万不能命名为mysql.py!
  3. 千万不能命名为mysql.py!
import mysql.connectordef get_connection():connection = mysql.connector.connect(host='localhost',database='python_db',user='root',password='root')return connectiondef close_connection(connection):if connection:connection.close()def read_database_version():try:connection = get_connection()cursor = connection.cursor()cursor.execute("SELECT version();")db_version = cursor.fetchone()print("You are connected to MySQL version: ", db_version)close_connection(connection)except (Exception, mysql.connector.Error) as error:print("Error while getting data", error)print("Question 1: Print Database version")
read_database_version()

MySQL 的连接和关闭

关于下列代码中 ** 的解释:python中星号的意义

import mysql.connector
from mysql.connector import errorcodeconfig = {'user': 'root','password': 'root','database': 'mydb','host': 'localhost','raise_on_warnings': True
}try:cnx = mysql.connector.connect(**config)
except mysql.connector.Error as err:    # if except happen will executeprint("Database operation ERR")if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:print("Something is wrong with your user name or password")elif err.errno == errorcode.ER_BAD_DB_ERROR:print("Database does not exist")else:print(err)
else:   # if no except happen will executecnx.close()print("Database operation OK")
finally:    # always executeprint("Finish")

MySQL创建表格及数据库

以下表格数据下载:employees database

import mysql.connector
from mysql.connector import errorcodeDB_NAME = 'employees'TABLES = {}
TABLES['employees'] = ("create table `employees` (""   `emp_no` int(11) NOT NULL AUTO_INCREMENT,""   `birth_date` date NOT NULL,""   `first_name` varchar(14) NOT NULL,""   `last_name` varchar(16) NOT NULL,""   `gender` enum('M', 'F') NOT NULL,""   `hire_date` date NOT NULL,""   primary key (`emp_no`)"") engine=InnoDB")TABLES['departments'] = ("create table `departments` (""   `dept_no` char(4) NOT NULL,""   `dept_name` varchar(40) NOT NULL,""   primary key (`dept_no`), unique key `dept_name` (`dept_name`)"") engine=InnoDB")TABLES['salaries'] = ("create table `salaries` (""   `emp_no` int(11) NOT NULL,""   `salary` int(11) NOT NULL,""   `from_date` date NOT NULL,""   `to_date` date NOT NULL,""   primary key (`emp_no`, `from_date`), key `emp_no` (`emp_no`),""   constraint `salaries_ibfk_1` foreign key (`emp_no`) ""       references `employees` (`emp_no`) on delete cascade"") engine=InnoDB")TABLES['dept_emp'] = ("create table `dept_emp` (""   `emp_no` int(11) NOT NULL,""   `dept_no` char(4) NOT NULL,""   `from_date` date NOT NULL,""   `to_date` date NOT NULL,""   primary key (`emp_no`, `dept_no`), key `emp_no` (`emp_no`),""   key `dept_no` (`dept_no`),""   constraint `dept_emp_ibfk_1` foreign key (`emp_no`) ""       references `employees` (`emp_no`) on delete cascade,""   constraint `dept_emp_ibfk_2` foreign key (`dept_no`) ""       references `departments` (`dept_no`) on delete cascade"") engine=InnoDB") TABLES['dept_manager'] = ("create table `dept_manager` (""   `emp_no` int(11) NOT NULL,""   `dept_no` char(4) NOT NULL,""   `from_date` date NOT NULL,""   `to_date` date NOT NULL,""   primary key (`emp_no`, `dept_no`),""   key `emp_no` (`emp_no`),""   key `dept_no` (`dept_no`),""   constraint `dept_manager_ibfk_1` foreign key (`emp_no`) ""       references `employees` (`emp_no`) on delete cascade,""   constraint `dept_manager_ibfk_2` foreign key (`dept_no`) ""       references `departments` (`dept_no`) on delete cascade"") engine=InnoDB")TABLES['titles'] = ("create table `titles` (""   `emp_no` int(11) NOT NULL,""   `title` varchar(50) NOT NULL,""   `from_date` date NOT NULL,""   `to_date` date NOT NULL,""   primary key (`emp_no`, `title`, `from_date`), key `emp_no` (`emp_no`),""   constraint `title_ibfk_1` foreign key (`emp_no`)""       references `employees` (`emp_no`) on delete cascade"") engine=InnoDB")def create_database(cursor):try:cursor.execute("create database {} default character set 'utf8'".format(DB_NAME))except mysql.connector.Error as err:print("Failed creating database: {}".format(err))exit(1)cnx = mysql.connector.connect(user='root', password='root')
cursor = cnx.cursor()try:cursor.execute("USE {}".format(DB_NAME))
except mysql.connector.Error as err:print("Database {} does not exists.".format(DB_NAME))if err.errno == errorcode.ER_BAD_DB_ERROR:create_database(cursor)print("Database {} created successfully.".format(DB_NAME))cnx.database = DB_NAMEelse:print(err)exit(1)for table_name in TABLES:table_description = TABLES[table_name]try:print("Creating table {}: ".format(table_name), end='')cursor.execute(table_description)except mysql.connector.Error as err:if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:print("already exist.")else:print(err.msg)else:print("OK")cursor.close()
cnx.close()

错误及原因

  1. ModuleNotFoundError: No module named 'mysql.connector'; 'mysql' is not a package
    以上错误是由于将本地的python文件命名成了mysql.py导致,改个名字就好了;
  2. mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported
    以上错误是由于安装的模块错了,我们需要安装mysql-connector-python,而安装成了mysql-connector;

http://www.ppmy.cn/news/1096667.html

相关文章

简明SQL别名指南:掌握AS实现列名更名

在 SQL 查询中,使用 {原始字段名} as {别名} 的语法来为查询结果的列赋予更直观的名称,以提高查询结果的可读性和可理解性。 以下是用到的表。 用AS更名 例如,查询表1的name字段,并将其更名为"名字",同时查…

ERROR: your rosdep installation has not been initialized yet

这个错误表示你的 rosdep 还没有初始化。rosdep 是一个 ROS 中的系统依赖管理工具,用于安装和配置需要的系统依赖包。在使用 rosdep 之前,需要先通过 rosdep update 命令初始化它。这个命令会连接远程服务器来更新 rosdep 的数据源,以获取所有支持的 ROS 版本和平台的依赖信息。…

laravel 报错误信息 Carbon\Exceptions\InvalidFormatException

Carbon\Exceptions\InvalidFormatException Unexpected data found. at vendor\nesbot\carbon\src\Carbon\Traits\Creator.php:687 683▕ return $instance; 684▕ } 685▕ 686▕ if (static::isStrictModeEnabled()) { ➜ 687…

thinkphp:数据库查询二,嵌套别的表的查询(别的表做子查询)

例子 从 vendors 表中选择记录。在 vendors 表中,筛选出具有满足以下条件的 vendor_code 值: 对应的采购订单(在 po_headers_all 表中)存在未完全接收的采购行(在 po_lines_all 表中)。相应的采购订单状态…

【LeetCode】19. 删除链表的倒数第 N 个结点

19. 删除链表的倒数第 N 个结点(中等) 方法:快慢指针 思路 为了找到倒数第 n 个节点,我们应该先找到最后一个节点,然后从它开始往前数 n-1 个节点就是要删除的节点。 对于一般情况:设置 fast 和 slow 两个…

视频监控/安防监控/AI视频分析/边缘计算/TSINGSEE青犀AI算法智慧仓储解决方案

随着全球经济与科学技术的双重推动,我国的仓储管理已经进入了高速发展时期,物流仓储也由简单的储藏仓库向智能化仓储转变。TSINGSEE青犀AI智慧仓储解决方案是利用先进的信息技术和物联网技术来提高仓储管理效率、降低成本的一种仓储管理模式。 方案功能 …

TOGAF架构内容—架构工件

一、 基本概念 创建架构工件是为了描述系统、解决方案或企业状态。本节中讨论的概念改编自ISO/IEC/IEEE 42010:2011和ISO/IEC/IEEE 15288:2015中包含的更正式的定义。它们如图3-1所示。 系统的“环境”是确定系统上所有影响的设置和环境的上下文。系统的环境包括发展、技术、商…