开始

安装MySQL驱动

$ python -m pip install mysql-connector-python

测试MySQL连接器

import mysql.connector

测试MySQL连接

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
) print(mydb)

创建数据库

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
) mycursor = mydb.cursor() mycursor.execute("CREATE DATABASE mydatabase")

创建表格

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")

插入数据

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record inserted.")

重要!。注意这个语句:mydb.commit()。它是进行修改的必要条件,否则就不会对表进行修改。

插入多行

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
] mycursor.executemany(sql, val) mydb.commit() print(mycursor.rowcount, "was inserted.")

获取插入的ID

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("Michelle", "Blue Village")
mycursor.execute(sql, val) mydb.commit() print("1 record inserted, ID:", mycursor.lastrowid)

查询

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers") myresult = mycursor.fetchall() for x in myresult:
print(x)

从表格中选择

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers") myresult = mycursor.fetchall() for x in myresult:
print(x)

注意:我们使用fetchall()方法,它从最后执行的语句中获取所有行。

选择列

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() mycursor.execute("SELECT name, address FROM customers") myresult = mycursor.fetchall() for x in myresult:
print(x)

如果只想查询一条数据,可以使用fetchone()方法。

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers") myresult = mycursor.fetchone() print(myresult)

Where条件

使用筛选器选择

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() sql = "SELECT * FROM customers WHERE address ='Park Lane 38'" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult:
print(x)

通配符

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() sql = "SELECT * FROM customers WHERE address LIKE '%way%'" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult:
print(x)

防止SQL注入

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() sql = "SELECT * FROM customers WHERE address = %s"
adr = ("Yellow Garden 2", ) mycursor.execute(sql, adr) myresult = mycursor.fetchall() for x in myresult:
print(x)

Order By

对结果进行排序

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() sql = "SELECT * FROM customers ORDER BY name" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult:
print(x)

使用DESC关键字对结果进行降序排序。

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() sql = "SELECT * FROM customers ORDER BY name DESC" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult:
print(x)

删除记录

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() sql = "DELETE FROM customers WHERE address = 'Mountain 21'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) deleted")

防止SQL注入

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() sql = "DELETE FROM customers WHERE address = %s"
adr = ("Yellow Garden 2", ) mycursor.execute(sql, adr) mydb.commit() print(mycursor.rowcount, "record(s) deleted")

删除表

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() sql = "DROP TABLE customers" mycursor.execute(sql)

更新数据

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) affected")

防止SQL注入

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() sql = "UPDATE customers SET address = %s WHERE address = %s"
val = ("Valley 345", "Canyon 123") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record(s) affected")

限制结果

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers LIMIT 5") myresult = mycursor.fetchall() for x in myresult:
print(x)

从另一个位置开始

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() mycursor.execute("SELECT * FROM customers LIMIT 5 OFFSET 2") myresult = mycursor.fetchall() for x in myresult:
print(x)

连接两张或更多数据表

# users 表
{ id: 1, name: 'John', fav: 154},
{ id: 2, name: 'Peter', fav: 154},
{ id: 3, name: 'Amy', fav: 155},
{ id: 4, name: 'Hannah', fav:},
{ id: 5, name: 'Michael', fav:}
# products
{ id: 154, name: 'Chocolate Heaven' },
{ id: 155, name: 'Tasty Lemons' },
{ id: 156, name: 'Vanilla Dreams' }
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
) mycursor = mydb.cursor() sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
INNER JOIN products ON users.fav = products.id" mycursor.execute(sql) myresult = mycursor.fetchall() for x in myresult:
print(x)

结束

MySQL的基本操作就是这样子了。

您的关注,是我的无限动力!

公众号 @生活处处有BUG

Python入门系列(十一)一篇搞定python操作MySQL数据库的更多相关文章

  1. Python高级特性: 12步轻松搞定Python装饰器

    12步轻松搞定Python装饰器 通过 Python 装饰器实现DRY(不重复代码)原则:  http://python.jobbole.com/84151/   基本上一开始很难搞定python的装 ...

  2. 一篇搞定Python正则表达式

    1. 正则表达式语法 1.1 字符与字符类 1 特殊字符:\.^$?+*{}[]()| 以上特殊字符要想使用字面值,必须使用\进行转义 2 字符类    1. 包含在[]中的一个或者多个字符被称为字符 ...

  3. 转载 12步轻松搞定python装饰器

    作者: TypingQuietly 原文链接: https://www.jianshu.com/p/d68c6da1587a 呵呵!作为一名教python的老师,我发现学生们基本上一开始很难搞定pyt ...

  4. 12步轻松搞定Python装饰器

    译者:寒寻 译文:http://www.cnblogs.com/imshome/p/8327438.html 原文:https://dzone.com/articles/understanding-p ...

  5. 第12天 | 12天搞定Python,让excel飞起来

    学了10多天Python基础知识了,是时候来点硬货了,看过<第1天 | 12天搞定Python,告诉你有什么用?>的老铁都知道,Python可用的领域挺多的.只是我长期待在企业,所以只能说 ...

  6. 第1天|12天搞定Python网络爬虫,吃里爬外?

    人力资源部漂亮的小MM,跑来问我:老陈,数据分析和爬虫究竟是关系呀?说实在的,我真不想理她,因为我一直认为这个跟她的工作关系不大,可一想到她负责我负责部门的招聘工作,我只好勉为其难地跟她说:数据分析, ...

  7. 2021升级版微服务教程6—Ribbon使用+原理+整合Nacos权重+实战优化 一篇搞定

    2021升级版SpringCloud教程从入门到实战精通「H版&alibaba&链路追踪&日志&事务&锁」 教程全目录「含视频」:https://gitee.c ...

  8. 一篇搞定RSA加密与SHA签名|与Java完全同步

    基础知识 什么是RSA?答:RSA是一种非对称加密算法,常用来对传输数据进行加密,配合上数字摘要算法,也可以进行文字签名. RSA加密中padding?答:padding即填充方式,由于RSA加密算法 ...

  9. 第4天 | 12天搞定Python,基础语法(下)

    为了方便你的学习,减轻负重,我特意将基础语法分成上下两部分.希望你喜欢这种方式,如果不喜欢,你可以跟我说,反正我是不会改的,哈哈~~. 如果上部分,你还没看的话,先去看<第4天 | 12天搞定P ...

随机推荐

  1. openGauss内核:SQL解析过程分析

    摘要:在传统数据库中SQL引擎一般指对用户输入的SQL语句进行解析.优化的软件模块.SQL的解析过程主要分为:词法.语法和语义分析. 本文分享自华为云社区< openGauss内核分析(三):S ...

  2. leetcode二叉树题目总结

    leetcode二叉树题目总结 题目链接:https://leetcode-cn.com/leetbook/detail/data-structure-binary-tree/ 前序遍历(NLR) p ...

  3. 利用laravel-echo主动向服务端发送消息,实现在线状态管理

    之前在网上翻了半天,也没有找到关于如何 通过laravel-echo主动发送消息 和 在laravel-websockets中自定义控制器 的文章或教程.无奈之下只能翻laravel-echo和lar ...

  4. 全国土壤阳离子交换量CEC空间分布数据

    数据下载链接:百度云下载链接​ 土壤阳离子交换量,简称CEC,是指土壤胶体所能吸附各种阳离子的总量.土壤阳离子交换量 cation exchange capacity 即CEC 是指土壤胶体所能吸附各 ...

  5. NLM5系列中继采集仪的常见问题

    NLM5系列中继采集采发仪常见问题 1.UART 通讯问题使用 UART 接口时一定要确认收发双方的通讯参数完全一致,包括通讯速率.数据位.校验位.停止位参数.NLM 在上电时会主动输出设备基本信息, ...

  6. html和css的常用语法代码详解

    前端html html 超文本标记语言.文本,图片,视频,音频. 网页基本信息 一个基础的网页具有的一些信息. <!-- 这是注释--> <!--!DOCTYPE网页约束规范--&g ...

  7. docker容器数据管理

    Docker容器数据卷 Docker中的数据可以存储在类似于虚拟机磁盘的介质中,在Docker中称为数据卷(Data Volume). 数据卷可以用来存储Docker应用的数据,也可以用来在Docke ...

  8. jdbc 04: 配置连接信息

    jdbc连接mysql,将需要的信息配置到文件中 package com.examples.jdbc.o4_配置连接信息; import java.sql.Connection; import jav ...

  9. SpringWeb 拦截器

    前言 spring拦截器能帮我们实现验证是否登陆.验签校验请求是否合法.预先设置数据等功能,那么该如何设置拦截器以及它的原理如何呢,下面将进行简单的介绍 1.设置 HandlerInterceptor ...

  10. 循环数组%操作下的一些解释(对于4.4UVA133的一些解释)

    1.循环数组一般不推荐通过建立相同的数组不断叠加来实现,虽然理论上是可行的,但是会浪费极大的空间,特别是对于大数据的情况下,程序一般会马上挂掉 2.循环数组的结构表示中的一种常用形式就是通过取余操作来 ...