【数据库】基于PyMySQL连接并使用数据库(代码示例)


前言

本文演示了如何基于PyMySQL使用代码来创建数据库连接、新建数据库表、向表中插入数据、查询表中的相关记录、更新表中的相关记录、删除表中的相关记录等操作,最后,要记得关闭游标和连接。


1、安装PyMySQL

如果是使用Anaconda来管理包和Python环境,则可以使用 s t e p 1 step1 step1 s t e p 2 step2 step2来创建一个独立的环境方便管理;如果不是可直接执行 s t e p 3 step3 step3将PyMySQL包安装到本地已有的Python环境中。

s t e p 1 : step1: step1创建一个虚拟环境

conda create -n use_mysql python=3.6

s t e p 2 : step2: step2激活虚拟环境

conda activate use_mysql

s t e p 3 : step3: step3使用清华源安装PyMySQL

pip install PyMySQL -i https://pypi.tuna.tsinghua.edu.cn/simple

2、打开要连接的数据库

我这里使用的是Navicat Premium 16连接一个名称为 “test” 的数据库。
在这里插入图片描述


3、创建数据库连接

import pymysql

# 设置数据库连接参数
db_params = {
    'host': 'localhost',         # 数据库服务器地址
    'user': 'root',              # 数据库用户名
    'password': '123456',        # 数据库密码
    'db': 'test',                # 要连接的数据库名称
    'charset': 'utf8mb4',        # 编码方式
}

# 创建数据库连接
try:
    connection = pymysql.connect(**db_params)
    print("Database connection successful.")
except pymysql.MySQLError as e:
    print(f"Error connecting to MySQL Platform: {e}")

运行代码,连接成功后控制台会打印输出 “Database connection successful.”


4、获取数据库版本

# 获取游标对象
cursor = connection.cursor()

# 获取数据库版本
cursor.execute("SELECT VERSION();")
data = cursor.fetchone()
print("Database version: %s " % data)

5、新建数据库表

# 检查表student是否已经存在于数据库test中
cursor.execute("SHOW TABLES LIKE 'STUDENT'")
result = cursor.fetchone()
if result:
    print("Table 'STUDENT' already exists.")
else:
    # 创建表
    cursor.execute("""
    CREATE TABLE STUDENT (
        num  INT NOT NULL,
        name  CHAR(20),
        age INT,  
        sex CHAR(10)
    )
    """)
    connection.commit()
    print("Table 'STUDENT' created successfully.")

6、向表中插入数据

# 向student表中插入数据
insert_sql_1 = "INSERT INTO STUDENT(num, name, age, sex) VALUES (1, 'zhangsan', 20, 'Man')"
insert_sql_2 = "INSERT INTO STUDENT(num, name, age, sex) VALUES (2, 'lisi', 18, 'Woman')"
insert_sql_3 = "INSERT INTO STUDENT(num, name, age, sex) VALUES (3, 'wangwu', 21, 'Man')"
insert_sql_4 = "INSERT INTO STUDENT(num, name, age, sex) VALUES (4, 'zhaoliu', 19, 'Woman')"
try:
    cursor.execute(insert_sql_1)
    cursor.execute(insert_sql_2)
    cursor.execute(insert_sql_3)
    cursor.execute(insert_sql_4)
    connection.commit()
    print("Successfully inserted data into the table.")
except Exception as e:  # 捕获所有异常
    print(f"An error occurred: {e}")
    connection.rollback()

运行代码后,回到 Navicat Premium 16 查看插入的数据。
在这里插入图片描述


7、查询表中的相关记录

# 查询student表中name字段值为'zhangsan'的所有记录
query_sql = "SELECT * FROM student WHERE name='zhangsan'"
try:
    cursor.execute(query_sql)
    results = cursor.fetchall()  # 获取所有查询结果
    print("The query results are as follows:")
    for row in results:
        print(row)  # 打印每一行结果
    connection.commit()
except Exception as e:  # 捕获所有异常
    print(f"An error occurred: {e}")
    connection.rollback()

8、更新表中的相关记录

# 更新student表中num字段值为3的记录的name字段为'newname':
update_sql = "UPDATE student SET name = 'newname' WHERE num = 3"
try:
    cursor.execute(update_sql)
    connection.commit()
    print("Successfully updated data in the table.")
except Exception as e:  # 捕获所有异常
    print(f"An error occurred: {e}")
    connection.rollback()

9、删除表中的相关记录

# 删除student表中num字段值为4的所有记录
delete_sql = "DELETE FROM student WHERE num = 4"
try:
    cursor.execute(delete_sql)
    connection.commit()
    print("Successfully deleted data from the table.")
except Exception as e:  # 捕获所有异常
    print(f"An error occurred: {e}")
    connection.rollback()

10、关闭游标和连接

# 关闭游标和连接
cursor.close()
connection.close()

完整代码

import pymysql

# 设置数据库连接参数
db_params = {
    'host': 'localhost',         # 数据库服务器地址
    'user': 'root',              # 数据库用户名
    'password': '123456',      # 数据库密码
    'db': 'test',                # 要连接的数据库名称
    'charset': 'utf8mb4',        # 编码方式
}

# 创建数据库连接
try:
    connection = pymysql.connect(**db_params)
    print("Database connection successful.")
except pymysql.MySQLError as e:
    print(f"Error connecting to MySQL Platform: {e}")

# 获取游标对象
cursor = connection.cursor()

# 获取数据库版本
cursor.execute("SELECT VERSION();")
data = cursor.fetchone()
print("Database version: %s " % data)

# 检查表student是否已经存在于数据库test中
cursor.execute("SHOW TABLES LIKE 'STUDENT'")
result = cursor.fetchone()
if result:
    print("Table 'STUDENT' already exists.")
else:
    # 创建表
    cursor.execute("""
    CREATE TABLE STUDENT (
        num  INT NOT NULL,
        name  CHAR(20),
        age INT,  
        sex CHAR(10)
    )
    """)
    connection.commit()
    print("Table 'STUDENT' created successfully.")

# 向student表中插入数据
insert_sql_1 = "INSERT INTO STUDENT(num, name, age, sex) VALUES (1, 'zhangsan', 20, 'Man')"
insert_sql_2 = "INSERT INTO STUDENT(num, name, age, sex) VALUES (2, 'lisi', 18, 'Woman')"
insert_sql_3 = "INSERT INTO STUDENT(num, name, age, sex) VALUES (3, 'wangwu', 21, 'Man')"
insert_sql_4 = "INSERT INTO STUDENT(num, name, age, sex) VALUES (4, 'zhaoliu', 19, 'Woman')"
try:
    cursor.execute(insert_sql_1)
    cursor.execute(insert_sql_2)
    cursor.execute(insert_sql_3)
    cursor.execute(insert_sql_4)
    connection.commit()
    print("Successfully inserted data into the table.")
except Exception as e:  # 捕获所有异常
    print(f"An error occurred: {e}")
    connection.rollback()

# 查询student表中name字段值为'zhangsan'的所有记录
query_sql = "SELECT * FROM student WHERE name='zhangsan'"
try:
    cursor.execute(query_sql)
    results = cursor.fetchall()  # 获取所有查询结果
    print("The query results are as follows:")
    for row in results:
        print(row)  # 打印每一行结果
    connection.commit()
except Exception as e:  # 捕获所有异常
    print(f"An error occurred: {e}")
    connection.rollback()

# 更新student表中num字段值为3的记录的name字段为'newname':
update_sql = "UPDATE student SET name = 'newname' WHERE num = 3"
try:
    cursor.execute(update_sql)
    connection.commit()
    print("Successfully updated data in the table.")
except Exception as e:  # 捕获所有异常
    print(f"An error occurred: {e}")
    connection.rollback()

# 删除student表中num字段值为4的所有记录
delete_sql = "DELETE FROM student WHERE num = 4"
try:
    cursor.execute(delete_sql)
    connection.commit()
    print("Successfully deleted data from the table.")
except Exception as e:  # 捕获所有异常
    print(f"An error occurred: {e}")
    connection.rollback()

# 关闭游标和连接
cursor.close()
connection.close()

  • 21
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 首先,你需要安装pymysql库,这可以使用pip进行安装: ``` pip install pymysql ``` 然后,你可以使用以下代码连接到MySQL数据库: ```python import pymysql # 连接数据库 connection = pymysql.connect(host='localhost', user='your_username', password='your_password', db='your_database_name', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: # 创建一个游标 with connection.cursor() as cursor: # 使用游标执行SQL查询 sql = "SELECT * FROM your_table" cursor.execute(sql) # 获取查询结果 result = cursor.fetchall() print(result) finally: # 关闭数据库连接 connection.close() ``` 在上面的代码中,你需要将'host', 'user', 'password', 'db'和'charset'替换为你自己的数据库连接信息。 在使用游标执行SQL查询之后,你可以使用fetchone()方法获取单行查询结果,或使用fetchall()方法获取所有行查询结果。 希望这对你有帮助! ### 回答2: 使用Python中的pymysql模块连接MySQL数据库代码如下: ```python import pymysql # 连接数据库 conn = pymysql.connect( host='localhost', # 数据库地址 port=3306, # 端口号 user='root', # 用户名 password='123456', # 密码 db='testdb' # 数据库名 ) # 创建游标对象 cursor = conn.cursor() # 执行SQL语句 sql = "SELECT * FROM students" cursor.execute(sql) # 获取查询结果 result = cursor.fetchall() for row in result: print(row) # 关闭游标和连接 cursor.close() conn.close() ``` 以上代码实现了使用pymysql模块连接MySQL数据库,首先使用connect()函数连接数据库,指定数据库的地址、端口号、用户名和密码等信息。然后创建游标对象cursor,通过execute()方法执行SQL查询语句,并使用fetchall()方法获取查询结果。最后,关闭游标和连接,释放资源。 请注意,上述代码中的host、port、user、password和db需要根据实际的数据库配置进行修改,以连接到正确的MySQL数据库。 ### 回答3: Python使用pymysql连接MySQL数据库代码如下: ```python import pymysql # 连接MySQL数据库 conn = pymysql.connect( host='localhost', # 数据库服务器地址 port=3306, # 数据库端口号 user='root', # 数据库用户名 password='123456', # 数据库密码 database='test' # 数据库名称 ) # 创建游标对象 cursor = conn.cursor() # 执行SQL查询语句 sql = "SELECT * FROM students" # 示例语句,可替换为实际的SQL查询语句 cursor.execute(sql) # 获取查询结果 result = cursor.fetchall() for row in result: print(row) # 断开连接 cursor.close() conn.close() ``` 以上代码首先导入pymysql模块,然后使用`pymysql.connect()`函数创建与MySQL数据库连接。在连接参数中,我们需要指定数据库服务器地址、端口号、用户名、密码和要连接数据库名称。 接着,我们创建了一个游标对象`cursor`,用于执行SQL查询语句。通过`cursor.execute()`函数执行SQL查询语句,并使用`cursor.fetchall()`函数获取查询结果。 最后,记得关闭游标和断开与数据库连接,以释放资源。 请根据实际情况修改代码中的连接参数和SQL查询语句,以适配你的MySQL数据库

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值