首页 > 数据库 >Python入门系列(十一)一篇搞定python操作MySQL数据库

Python入门系列(十一)一篇搞定python操作MySQL数据库

时间:2022-09-06 21:13:58浏览次数:56  
标签:connector Python MySQL mycursor python sql mysql import mydb

开始

安装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

标签:connector,Python,MySQL,mycursor,python,sql,mysql,import,mydb
From: https://www.cnblogs.com/bugs-in-life/p/16663299.html

相关文章

  • mysqldump throws: Unknown table 'COLUMN_STATISTICS' in information_schema (1109)
    AWSRDS_MYSQL8.0执行mysqldump报以下错误mysqldumpthrows:Unknowntable'COLUMN_STATISTICS'ininformation_schema(1109) 具体$>mysqldump--single-tra......
  • 硬核解析MySQL的MVCC实现原理,面试官看了都直呼内行
    1.什么是MVCCMVCC全称是Multi-VersionConcurrencyControl(多版本并发控制),是一种并发控制的方法,通过维护一个数据的多个版本,减少读写操作的冲突。如果没有MVCC,想要实现......
  • python fastapi + uvicorn 记录日志的最佳实践,结合nb_log
      pythonfastapi+uvicorn记录日志的最佳实践,要记录对fastapi什么时候请求了什么url和入参,只需要记录uvicorn命名空间的日志就可以了。文章使用nb_log五彩日志来......
  • 奶奶常说,黑白照片看的不清晰,还好我会Python,分分钟给她变成彩色的~
    咳咳~其实是奶奶常说,艾欧尼亚昂扬不灭,正义将指引着我们! 好吧,并不是奶奶说,只是最近回家发现一些黑白老照片,看着不够清晰,然后实验了一波用Python把老照片变成彩......
  • [安装配置] Linux安装MySQL
    第一步:查看mysql相关的软件查询当前系统中安装的名称带mysql的软件rpm-qa|grepmysql查询当前系统中安装的名称带mariadb的软件rpm-qa|grepmariadb第二步:卸载......
  • jenkins+python构建项目
    1.下载jenkinswindows版本2.安装:需要检验端口,因为本机8080被别的项目占用了,选择了80端口3.新建一个free风格项目  配置:github,github管理代码,相当于本地代码需要推......
  • centos 7.X 安装python3.X 使得python3.X 和 python2.x共存
    https://www.cnblogs.com/JahanGu/p/7452527.html(以亲试)https://blog.csdn.net/eastlhu/article/details/74931913https://www.cnblogs.com/FZfangzheng/p/7588944.html......
  • python(三)函数
    (六)字符串的比较is是通过比较两个对象的内存地址,查看内存地址的方法是id()in是包含==是类型和内容一致a=1b=1print(id(a))print(id(b))ifaisb: print......
  • pythonⅢ
    '''字符串的比较is:看通过id()对象的内存地址,查看内存地址的方式in:包含==:类型及内容一致'''a=1b=1print(id(a))print(id(b))ifaisb:    print('a和b内存地址都一样......
  • mysql 主备模式搭建过程
    MySQL主备搭建1.主库配置以下所有操作均在主服务器上执行1)创建用户并授权createuserslaveidentifiedwithmysql_native_passwordby'123456'mysql>GRANTREPLICA......