Python3 MySQL(PyMySQL)学习笔记

1. MySQL是什么?

MySQL是一种开源关系型数据库管理系统(RDBMS),它使用SQL语言进行查询和管理数据。MySQL是最受欢迎的数据库之一,因为它易于学习和使用,并可用于各种应用程序。

2. 安装PyMySQL

PyMySQL是一个Python库,用于在Python中连接和操作MySQL数据库。

使用pip命令安装PyMySQL:

Copy Code
pip install PyMySQL

3. 连接到MySQL数据库

在Python中连接到MySQL数据库需要以下步骤:

  1. 导入PyMySQL模块
  2. 连接到数据库
  3. 创建游标对象
  4. 执行SQL语句
  5. 关闭游标和连接

下面是一个连接到MySQL数据库并查询所有数据的示例代码:

pythonCopy Code
import pymysql # 连接到数据库 conn = pymysql.connect( host='localhost', port=3306, user='root', password='password', db='testdb' ) # 创建游标对象 cursor = conn.cursor() # 执行SQL语句 sql = "SELECT * FROM students" cursor.execute(sql) # 输出查询结果 results = cursor.fetchall() for row in results: print(row) # 关闭游标和连接 cursor.close() conn.close()

4. 插入数据

插入数据需要编写INSERT语句并执行它。下面是一个向students表中插入新数据的示例代码:

pythonCopy Code
import pymysql # 连接到数据库 conn = pymysql.connect( host='localhost', port=3306, user='root', password='password', db='testdb' ) # 创建游标对象 cursor = conn.cursor() # 执行INSERT语句 sql = "INSERT INTO students(name, age, gender) VALUES (%s, %s, %s)" values = ('Tom', 20, 'male') cursor.execute(sql, values) # 提交更改 conn.commit() # 关闭游标和连接 cursor.close() conn.close()

5. 更新数据

更新数据需要编写UPDATE语句并执行它。下面是一个更新students表中一行数据的示例代码:

pythonCopy Code
import pymysql # 连接到数据库 conn = pymysql.connect( host='localhost', port=3306, user='root', password='password', db='testdb' ) # 创建游标对象 cursor = conn.cursor() # 执行UPDATE语句 sql = "UPDATE students SET age = %s WHERE name = %s" values = (21, 'Tom') cursor.execute(sql, values) # 提交更改 conn.commit() # 关闭游标和连接 cursor.close() conn.close()

6. 删除数据

删除数据需要编写DELETE语句并执行它。下面是一个从students表中删除一行数据的示例代码:

pythonCopy Code
import pymysql # 连接到数据库 conn = pymysql.connect( host='localhost', port=3306, user='root', password='password', db='testdb' ) # 创建游标对象 cursor = conn.cursor() # 执行DELETE语句 sql = "DELETE FROM students WHERE name = %s" values = ('Tom',) cursor.execute(sql, values) # 提交更改 conn.commit() # 关闭游标和连接 cursor.close() conn.close()

以上是使用Python3和PyMySQL操作MySQL数据库的基本知识和实例。