Table of Contents
1. Table and key concepts
%%PRE_BLOCK_0%%
8. Create company database
9. Obtain company information
10. Aggregation function
11. Universal sub-element
Twelve, Union
Thirteen, Connection
Fourteen, Subquery
Fifteen, On delete
Home Backend Development Python Tutorial How to connect to MySQL using Python

How to connect to MySQL using Python

May 12, 2023 am 11:55 AM
mysql python

1. Table and key concepts

How to connect to MySQL using Python

How to connect to MySQL using Python

How to connect to MySQL using Python

#Primary key: Can uniquely represent the data (multiple lists can be set as primary keys)

How to connect to MySQL using Python

Set foreign keys to connect tables, and the foreign keys must be the primary keys of other tables (foreign keys The key can also be set as the primary key of its own table)

2. Create a database

CREATE DATABASE `sql_tutorial`;    --创建资料库
SHOW databases;    --展示资料库
drop database `sql_tutorial`;    --删除资料库

– as a comment

; as the format of the end command

How to connect to MySQL using Python

3. Create a table

MySQL data form:

    ##INT --Integer
  • DECIMAL(m,n) --The number (3,2) with a decimal point is 2.33. There are m digits in total and the decimal point has n digits
  • VARCHAR(n ) --String
  • BLOB --Picture video file...(binary data)
  • DATE --Date (yyyy-mm -dd)
  • TIMESTAMP --record time (yyyy-mm-dd hh:mm:ss)
  • CREATE DATABASE `sql_tutorial`;  -- 创建资料库
    SHOW databases;        -- 展示资料库
    use `sql_tutorial`; -- 选择使用的资料库
    
    create table student(
            `student_id` int primary key, -- 第一列
        `name` varchar(20), -- 第二列
        `major` varchar(20) -- 第三列,20指的是最大字符长度
    ); -- 创建表格并设计属性
    
    describe `student`; -- 展示表格
    drop table `student`; -- 删除表格
    
    alter table `student` add gpa decimal(3,2); -- 增加资料属性
    alter table `student` drop column gpa ; -- 删除资料属性

How to connect to MySQL using Python4. Storing data

create table student(
        `student_id` int primary key, -- 第一列
    `name` varchar(20), -- 第二列
    `major` varchar(20) -- 第三列,20指的是最大字符长度
); -- 创建表格并设计属性
select * from `student`; -- 搜索表格的全部资料

insert into `student` values(1,'小白','历史'); -- 写入表格数据
insert into `student` values(2,'小黑','生物'); -- 写入表格数据
insert into `student` values(3,'小绿',null); -- 写入表格数据,null为空

insert into `student`(`name`,`major`,`student_id`) values('小蓝','英语','4'); -- 按照设置写入表格数据
insert into `student`(`major`,`student_id`) values('英语','5'); -- 按照设置写入表格数据,没有的数据则为空白null

How to connect to MySQL using Python5. Restrictions

create table student(
        `student_id` int primary key, -- 第一列
    `name` varchar(20) not null, -- 第二列,not null指这个属性不可以为空
    `major` varchar(20) unique -- 第三列,20指的是最大字符长度,unique指每个值不可以重复
); -- 创建表格并设计属性

create table student(
        `student_id` int primary key auto_increment, -- 第一列,auto_increment自动会加一
    `name` varchar(20), -- 第二列,not null指这个属性不可以为空
    `major` varchar(20) default '历史' -- 第三列,20指的是最大字符长度,default指预设值,如果没有写该属性,则为预设值
); -- 创建表格并设计属性
drop table `student`;
select * from `student`; -- 搜索表格的全部资料

insert into `student`(`name`,`major`) values('小蓝','英语'); -- 按照设置写入表格数据
insert into `student`(`name`) values('小黑'); -- 按照设置写入表格数据

How to connect to MySQL using Python6. Modifying and deleting data

Conditions:

>,<,>=,<=,=,<>

set sql_safe_updates = 0; -- 把预设更新模式关闭,这样更新操作才可以成功
create table student(
        `student_id` int primary key auto_increment, -- 第一列
    `name` varchar(20), -- 第二列
    `major` varchar(20), -- 第三列,20指的是最大字符长度
    `score` int
); -- 创建表格并设计属性
drop table `student`;
select * from `student`; -- 搜索表格的全部资料

insert into `student`(`name`,`major`) values(&#39;小蓝&#39;,&#39;英语&#39;); -- 按照设置写入表格数据
insert into `student`(`name`,`major`) values(&#39;小白&#39;,&#39;化学&#39;); -- 按照设置写入表格数据
insert into `student`(`name`,`major`) values(&#39;小黑&#39;,&#39;生物&#39;); -- 按照设置写入表格数据
update `student` -- 更新哪个表格
set `major` = &#39;英语文学&#39; -- 将什么更新成什么
where `major` = &#39;英语&#39;; -- 将其中谁的什么进行更新
-- 还可以进行多个更新
update `student` -- 更新哪个表格
set `major` = &#39;生化&#39; -- 将什么更新成什么
where `major` = &#39;生物&#39; or `major` = &#39;化学&#39; ; -- 将其中谁的什么进行更新
update `student` -- 更新哪个表格
set `name` = &#39;小辉&#39;,`major` = &#39;生化&#39; -- 将什么更新成什么
where `student_id`=1 ; -- 将其中谁的什么进行更新
-- 不加条件则都改
update `student` -- 更新哪个表格
set `major` = &#39;物理&#39;; -- 将其中谁的什么进行更新,都改成了生化

delete from `student`
where `student_id` = 3; -- 删除表格中的数据
-- 条件也可以设置多个
delete from `student`
where `name` = &#39;小白&#39; and `major`=&#39;物理&#39;; -- 删除表格中的数据

delete from `student`; -- 删除所有的资料
7. Obtain information

-- 取得资料
select * from `student`; -- 取得表格的全部资料
select `name` from `student`; -- 只取得表格的对应数据
select `name`, `major` from `student`; -- 取得表格的对应多个数据
select * from `student` ORDER BY `score`; -- 取得表格的全部资料,并排序(默认正序)
select * from `student` ORDER BY `score` DESC; -- 取得表格的全部资料,并排序(由高到低,asc是由低到高)
select * from `student` ORDER BY `score` ,`student_id`; -- 取得表格的全部资料,并排序(先有score做排序,score中相同的再由student_id做排序)
select * from `student` LIMIT 3 ; -- 限制资料范围
select * from `student` ORDER BY `score` LIMIT 3 ; -- 排序并限制资料范围
select * from `student` where `major`= &#39;英语&#39;; -- 查找对应资料
select * from `student` where `major`= &#39;英语&#39; and `student_id` = 1; -- 查找对应资料(多条件)
select * from `student` where `major` in(&#39;历史&#39;,&#39;英语&#39;,&#39;生物&#39;); -- 查找对应资料(多条件)1

8. Create company database

CREATE DATABASE `sql_tutorial`;  -- 创建资料库
SHOW databases;        -- 展示资料库
use `sql_tutorial`; -- 选择使用的资料库

create table `employee`(
        `emp_id` int primary key, -- 第一列
    `name` varchar(20), -- 第二列,20指的是最大字符长度
    `bath_date` date, -- 第三列
    `sex` varchar(1),
    `salary` int,
    `branch_id` int,
    `sup_id` int
); -- 创建表格并设计属性
create table `branch`(
        `branch_id` int primary key , -- 第一列
    `branch_name` varchar(20), -- 第二列
    `manager_id` int, -- 第三列,20指的是最大字符长度
    foreign key (`manager_id`) references `employee`(`emp_id`) on delete set null -- 设置好外键(选择什么是并对应什么表格的什么属性)
); -- 创建表格并设计属性
-- 补充外键(外表格对应)
alter table `employee` -- 在什么表格上进行更新
add foreign key(`branch_id`) -- 在他的什么属性上
references `branch`(`branch_id`) -- 从哪的什么属性对应
on delete set null;
-- 补充外键(内表格对应)
alter table `employee` -- 在什么表格上进行更新
add foreign key(`sup_id`) -- 在他的什么属性上
references `employee`(`emp_id`) -- 从哪的什么属性对应
on delete set null;
create table `client`(
        `client_id` int primary key , -- 第一列
    `client_name` varchar(20), -- 第二列
    `phone` varchar(20) -- 第三列,20指的是最大字符长度
); -- 创建表格并设计属性
create table `works_with`(
        `emp_id` int, -- 第一列
    `client_id` int, -- 第二列
    `total_sales` int, -- 第三列,20指的是最大字符长度
    primary key(`emp_id`,`client_id`),
    foreign key (`emp_id`) references `employee`(`emp_id`) on delete cascade, -- 设置好外键(选择什么是并对应什么表格的什么属性)
        foreign key (`client_id`) references `client`(`client_id`) on delete cascade -- 设置好外键(选择什么是并对应什么表格的什么属性)
); -- 创建表格并设计属性
-- 当增加资料冲突的时候可以先将其设置为null然后再更新
insert into `branch` values(1,&#39;研发&#39;,null);
insert into `employee` values(206,&#39;xiaohuang&#39;,&#39;1998-10-08&#39;,&#39;F&#39;,50000,1,null);
update `branch`
set `manager_id` = 206
where `branch_id` = 1;

9. Obtain company information

-- 取得对应表格所有资料
select * from `employee`;
-- 取得对应表格所有资料并排序(默认低到高)
select * from `employee` order by `salary`; -- 低为加desc
-- 增加限制取出条件
select * from `employee` order by `salary` desc limit 3 ; -- 取出前三高
-- 取出对应属性
select  `name` from `employee` ;
-- 取出对应属性的内容(且不重复)
select distinct `name` from `employee` ;

10. Aggregation function

-- 取得人数
select count(*) from `employee`; -- 统计几笔资料
select count(`sup_id`) from `employee`; -- 统计对应属性资料个数(null不计入)
-- 增加条件取数
select count(*)
from `employee`
where `bath_date` > &#39;1970-01-01&#39; and `sex` = &#39;F&#39;; -- 统计几笔资料
-- 计算对应的属性的平均
select avg(`salary`) from `employee`;
-- 计算对应的属性的总和
select sum(`salary`) from `employee`;
-- 取得最高的
select max(`salary`) from `employee`;
-- 取得最低的
select min(`salary`) from `employee`;

11. Universal sub-element

-- %表示多个子元,_表示一个子元
-- 取得尾数335的数据
select * from `client` where `phone` like &#39;%335&#39;;
-- 取得姓艾的
select * from `client` where `client_name` like &#39;艾%&#39;;
-- 取得生日是10月的
select * from `employee` where `bath_date` like &#39;_____10%&#39;;

Twelve, Union

-- 员工与客户合并为一列(类型必须相同)
select `name` from `employee`
union
select `client_name` from `client`;
-- 多个数据合并为多列(类型必须相同)
select `emp_id`, `name` from `employee`
union
select `client_id`, `client_name` from `client`;
-- 多个数据合并为多列(类型必须相同)顺便改个名
select `emp_id` as `total_id`, `name` as `total_name` from `employee`
union
select `client_id`, `client_name` from `client`;

Thirteen, Connection

-- 连接
-- 取得所有部门经理名字,这就需要先确定部门再确定经理(二表相连)
select * from `employee` join `branch` on `emp_id` = `manager_id`;
-- 还可以写成
select * from `employee` join `branch` on `employee`.`emp_id` = `branch`.`manager_id`;
-- 附加条件
select * from `employee` left join `branch` on `employee`.`emp_id` = `branch`.`manager_id`; -- 左边的表格(join的左边)返回全部数据,右边的必须满足才可

Fourteen, Subquery

-- 查询套查询
select `name` from `employee`
where `emp_id` = (
        select `manager_id`
    from `branch`
    where `branch_name` = &#39;研发&#39;
); -- 查找研发部门的经理名字
select `emp_id` from `employee`
where `emp_id` in (
        select `emp_id` 
        from `works_with`
        where `total_sales` > 50000
); -- 销售资金超50000的人有哪些

Fifteen, On delete

    On delete set null The function is that if the data is deleted (or no longer corresponds to it), it will be set to null
  • On delete decade If the corresponding data is deleted (or If it cannot be matched), then the data in the table will be deleted
Note:

cannot be set to on delete set nullcreate when it is the primary key table `branch`(

        `branch_id` int primary key , -- 第一列
    `branch_name` varchar(20), -- 第二列
    `manager_id` int, -- 第三列,20指的是最大字符长度
    foreign key (`manager_id`) references `employee`(`emp_id`) on delete set null -- 设置好外键(选择什么是并对应什么表格的什么属性)
); -- 创建表格并设计属性
create table `works_with`(
        `emp_id` int, -- 第一列
    `client_id` int, -- 第二列
    `total_sales` int, -- 第三列,20指的是最大字符长度
    primary key(`emp_id`,`client_id`),
    foreign key (`emp_id`) references `employee`(`emp_id`) on delete cascade, -- 设置好外键(选择什么是并对应什么表格的什么属性)
        foreign key (`client_id`) references `client`(`client_id`) on delete cascade -- 设置好外键(选择什么是并对应什么表格的什么属性)
); -- 创建表格并设计属性

16. Python connection to MySQL
# 导入功能包(mysql-connector-python)
import mysql.connector

# 创入连线
connection = mysql.connector.connect(host=&#39;localhost&#39;,  # mysql的位置
                                     port=&#39;3306&#39;,  # 连接通道
                                     user=&#39;root&#39;,   # 使用者名称
                                     password=&#39;123456&#39;)  # 使用者密码
&#39;&#39;&#39;connection = mysql.connector.connect(host=&#39;localhost&#39;,  # mysql的位置
                                     port=&#39;3306&#39;,  # 连接通道
                                     user=&#39;root&#39;,   # 使用者名称
                                     password=&#39;123456&#39;,   # 使用者密码
                                     database=&#39;sql_tutorial&#39;)  # 直接打开目标资料库&#39;&#39;&#39;

# 告知开始使用操作
cursor = connection.cursor()
# 在对mysql操作时即用该格式:cursor.execute("你要执行的mysql语句命令")

# 创建资料库
# cursor.execute("CREATE DATABASE `qq`;")

# 取得所有资料库名称
cursor.execute("show databases;")
records = cursor.fetchall()  # 取出回传资料库
for r in records:
    print(r)  # 因为回传列表,为便于观察,进行循环打印

# 选择资料库
cursor.execute("use `sql_tutorial`;")

# 创建表格

# 告知关闭操作
cursor.close()
# 若要懂资料进行修改需要结尾加一个指令,这样才能提交指令生效
connection.commit()
# 关闭连线
connection.close()

The above is the detailed content of How to connect to MySQL using Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1545
276
How to run Python code in Sublime Text? How to run Python code in Sublime Text? Aug 16, 2025 am 04:58 AM

Make sure that Python is installed and added to the system PATH, run python--version or python3--version verification through the terminal; 2. Save the Python file as a .py extension, such as hello.py; 3. Create a custom build system in SublimeText, Windows users use {"cmd":["python","-u","$file"]}, macOS/Linux users use {"cmd":["python3

How to debug a Python script in VSCode How to debug a Python script in VSCode Aug 16, 2025 am 02:53 AM

To debug Python scripts, you need to first install the Python extension and configure the interpreter, then create a launch.json file to set the debugging configuration, then set a breakpoint in the code and press F5 to start the debugging. The script will be paused at the breakpoint, allowing checking variables and step-by-step execution. Finally, by checking the problem by viewing the console output, adding logs or adjusting parameters, etc., to ensure that the debugging process is simple and efficient after the environment is correct.

How does the yield keyword work in Python How does the yield keyword work in Python Aug 15, 2025 am 08:23 AM

The yield keyword is used to define a generator function, so that it can pause execution and return values one by one, and then recover from the pause; the generator function returns a generator object, has lazy evaluation characteristics, and can save memory. It is suitable for handling scenarios such as large files, streaming data, and infinite sequences. The generator is an iterator that supports next() and for loops, but cannot be rewind and must be recreated to iterate again.

How to create a Python project in Sublime Text? How to create a Python project in Sublime Text? Aug 16, 2025 am 08:53 AM

InstallSublimeTextandPython,thenconfigureabuildsystembycreatingaPython3.sublime-buildfilewiththeappropriatecmdandselectorsettingstoenablerunningPythonscriptsviaCtrl B.2.OrganizeyourprojectbycreatingadedicatedfolderwithPythonfilesandsupportingdocument

How to handle errors in MySQL stored procedures How to handle errors in MySQL stored procedures Aug 17, 2025 am 06:50 AM

UseDECLARECONTINUEorDECLAREEXITHANDLERtospecifyerrorhandlingbehavior,whereCONTINUEallowsexecutiontoproceedafterhandlingtheerror,andEXITstopsexecutionofthecurrentblock;2.HandleerrorsusingSQLSTATEvalues(e.g.,'23000'forconstraintviolations),MySQLerrorco

How to select data from a table in MySQL? How to select data from a table in MySQL? Aug 19, 2025 pm 01:47 PM

To select data from MySQL table, you should use SELECT statement, 1. Use SELECTcolumn1, column2FROMtable_name to obtain the specified column, or use SELECT* to obtain all columns; 2. Use WHERE clause to filter rows, such as SELECTname, ageFROMusersWHEREage>25; 3. Use ORDERBY to sort the results, such as ORDERBYageDESC, representing descending order of age; 4. Use LIMIT to limit the number of rows, such as LIMIT5 to return the first 5 rows, or use LIMIT10OFFSET20 to implement paging; 5. Use AND, OR and parentheses to combine

How to get the last inserted ID in MySQL? How to get the last inserted ID in MySQL? Aug 16, 2025 am 10:38 AM

To get the last inserted ID in MySQL, you should use the LAST_INSERT_ID() function. This function returns the last self-increment ID in the current session after insertion. It has session security and is not affected by other clients. It can still obtain the correct result even after executing other queries. If no insertion occurs, it will return 0. For multi-line insertion, return the first generated ID, such as executing INSERTINTOusers(name,email)VALUES('JohnDoe','john@example.com'); followed by SELECTLAST_INSERT_ID(); to obtain the ID of the newly inserted user. When using PHP, you can use $mysqli-&

What is the difference between REAL, DOUBLE, and FLOAT in MySQL? What is the difference between REAL, DOUBLE, and FLOAT in MySQL? Aug 17, 2025 am 09:53 AM

REALisasynonymforDOUBLEbydefault,butcanactasFLOATifREAL_AS_FLOATSQLmodeisenabled;FLOATuses4byteswith~7-digitprecisionforsingle-precisionvalues,DOUBLEuses8byteswith~15–17-digitprecisionfordouble-precisionvalues,andREAL’sbehaviordependsonSQLmode,making

See all articles