首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

Python筑基之旅-MySQL数据库(四)

  • 25-03-03 04:23
  • 3920
  • 13896
blog.csdn.net

目录

一、数据表操作

1、新增记录

1-1、用mysql-connector-python库

1-2、用PyMySQL库

1-3、用PeeWee库

1-4、用SQLAlchemy库

2、删除记录

2-1、用mysql-connector-python库

2-2、用PyMySQL库

2-3、用PeeWee库

2-4、用SQLAlchemy库

3、修改记录

3-1、用mysql-connector-python库

3-2、用PyMySQL库

3-3、用PeeWee库

3-4、用SQLAlchemy库

4、查询记录

4-1、用mysql-connector-python库

4-2、用PyMySQL库

4-3、用PeeWee库

4-4、用SQLAlchemy库

二、推荐阅读

1、Python函数之旅

2、Python算法之旅

3、博客个人主页

一、数据表操作

        在MySQL服务器上已有数据库test_database,且该数据库下已有数据表myelsa_table,此数据表包含4个字段:name,ID_Card,age,city,现借助第三方库对该数据表进行增、删、改、查等操作。

1、新增记录

1-1、用mysql-connector-python库
  1. import mysql.connector
  2. # 数据库连接配置
  3. config = {
  4. 'username': 'root', # 替换为你的MySQL用户名
  5. 'password': '123456', # 替换为你的MySQL密码
  6. 'host': '127.0.0.1', # 如果数据库在远程服务器上,请替换为相应的主机名或IP地址
  7. 'database': 'test_database', # 数据库名
  8. }
  9. # 定义要插入的数据
  10. new_record = {
  11. 'name': 'Myelsa',
  12. 'ID_Card': '443689564710526448',
  13. 'age': 18,
  14. 'city': 'Guangzhou'
  15. }
  16. # SQL插入语句
  17. insert_query = """
  18. INSERT INTO myelsa_table (name, ID_Card, age, city)
  19. VALUES (%s, %s, %s, %s)
  20. """
  21. try:
  22. # 连接到数据库
  23. cnx = mysql.connector.connect(**config)
  24. cursor = cnx.cursor()
  25. # 执行SQL插入语句
  26. cursor.execute(insert_query, (new_record['name'], new_record['ID_Card'], new_record['age'], new_record['city']))
  27. # 提交更改
  28. cnx.commit()
  29. print("Record inserted successfully!")
  30. except mysql.connector.Error as err:
  31. print(f"Error: '{err}'")
  32. finally:
  33. # 关闭游标和连接
  34. if cursor:
  35. cursor.close()
  36. if cnx.is_connected():
  37. cnx.close()
1-2、用PyMySQL库
  1. import pymysql
  2. # 数据库连接配置
  3. config = {
  4. 'user': 'root', # 替换为你的MySQL用户名
  5. 'password': '123456', # 替换为你的MySQL密码
  6. 'host': '127.0.0.1', # 如果数据库在远程服务器上,请替换为相应的主机名或IP地址
  7. 'database': 'test_database', # 数据库名
  8. 'charset': 'utf8mb4', # 添加字符集配置,防止编码问题
  9. 'cursorclass': pymysql.cursors.DictCursor # 使用字典游标以便轻松访问列名
  10. }
  11. # 定义要插入的数据
  12. new_record = {
  13. 'name': 'Myelsa',
  14. 'ID_Card': '443689564710526448',
  15. 'age': 18,
  16. 'city': 'Guangzhou'
  17. }
  18. # SQL插入语句
  19. insert_query = """
  20. INSERT INTO myelsa_table (name, ID_Card, age, city)
  21. VALUES (%s, %s, %s, %s)
  22. """
  23. try:
  24. # 连接到数据库
  25. cnx = pymysql.connect(**config)
  26. with cnx.cursor() as cursor:
  27. # 使用with语句确保游标在使用完毕后被关闭
  28. # 执行SQL插入语句
  29. cursor.execute(insert_query, (new_record['name'], new_record['ID_Card'], new_record['age'], new_record['city']))
  30. # 提交更改
  31. cnx.commit()
  32. print("Record inserted successfully!")
  33. except pymysql.Error as err:
  34. print(f"Error: '{err}'")
  35. # 使用with语句连接数据库时,在with块结束后连接将自动关闭
  36. # 如果没有使用with语句,需要显式关闭连接
  37. if cnx.open:
  38. cnx.close()
1-3、用PeeWee库
  1. from peewee import *
  2. # 数据库连接配置
  3. db = MySQLDatabase('test_database', user='root', password='123456', host='127.0.0.1')
  4. # 定义模型
  5. class MyelsaTable(Model):
  6. name = CharField()
  7. ID_Card = CharField()
  8. age = IntegerField()
  9. city = CharField()
  10. class Meta:
  11. database = db
  12. table_name = 'myelsa_table'
  13. # 连接到数据库
  14. db.connect()
  15. # 创建表(如果尚不存在)
  16. db.create_tables([MyelsaTable])
  17. # 插入数据
  18. new_record = {
  19. 'name': 'Myelsa',
  20. 'ID_Card': '443689564710526448',
  21. 'age': 18,
  22. 'city': 'Guangzhou'
  23. }
  24. try:
  25. MyelsaTable.create(
  26. name=new_record['name'],
  27. ID_Card=new_record['ID_Card'],
  28. age=new_record['age'],
  29. city=new_record['city']
  30. )
  31. print("Record inserted successfully!")
  32. except IntegrityError as e:
  33. print(f"Error: '{e}'")
  34. finally:
  35. # 关闭数据库连接
  36. db.close()
1-4、用SQLAlchemy库
  1. from sqlalchemy import create_engine, Column, Integer, String
  2. from sqlalchemy.ext.declarative import declarative_base
  3. from sqlalchemy.orm import sessionmaker
  4. from sqlalchemy.exc import SQLAlchemyError
  5. # 定义基类
  6. Base = declarative_base()
  7. # 定义数据库模型类
  8. class MyElsaTable(Base):
  9. __tablename__ = 'myelsa_table'
  10. ID_Card = Column(String, primary_key=True)
  11. name = Column(String)
  12. age = Column(Integer)
  13. city = Column(String)
  14. def __repr__(self):
  15. return f"{self.ID_Card}, name={self.name}, age={self.age}, city={self.city})>"
  16. # 数据库连接配置
  17. config = {
  18. 'username': 'root', # 替换为你的MySQL用户名
  19. 'password': '123456', # 替换为你的MySQL密码
  20. 'host': '127.0.0.1', # 如果数据库在远程服务器上,请替换为相应的主机名或IP地址
  21. 'database': 'test_database', # 数据库名
  22. }
  23. # 创建数据库引擎
  24. engine = create_engine(
  25. f'mysql+pymysql://{config["username"]}:{config["password"]}@{config["host"]}/{config["database"]}')
  26. # 确保所有表都已创建(可选)
  27. Base.metadata.create_all(engine)
  28. # 创建会话类
  29. Session = sessionmaker(bind=engine)
  30. # 定义要插入的数据
  31. new_record = {
  32. 'name': 'Myelsa',
  33. 'ID_Card': '443689564710526448',
  34. 'age': 18,
  35. 'city': 'Guangzhou'
  36. }
  37. try:
  38. # 使用上下文管理器自动管理会话
  39. with Session() as session:
  40. # 创建新的模型实例
  41. new_entry = MyElsaTable(**new_record)
  42. # 将新实例添加到会话中
  43. session.add(new_entry)
  44. # 提交更改
  45. session.commit()
  46. print("Record inserted successfully!")
  47. except SQLAlchemyError as e:
  48. print(f"Error: '{e}'")
  49. # 在使用上下文管理器时,无需显式回滚,因为上下文管理器会在退出时处理它

2、删除记录

2-1、用mysql-connector-python库
  1. import mysql.connector
  2. # 数据库连接配置
  3. config = {
  4. 'username': 'root', # 替换为你的MySQL用户名
  5. 'password': '123456', # 替换为你的MySQL密码
  6. 'host': '127.0.0.1', # 如果数据库在远程服务器上,请替换为相应的主机名或IP地址
  7. 'database': 'test_database', # 数据库名
  8. }
  9. # 要删除的记录的ID_Card值
  10. id_card_to_delete = '443689564710526448'
  11. # SQL删除语句
  12. delete_query = """
  13. DELETE FROM myelsa_table
  14. WHERE ID_Card = %s
  15. """
  16. try:
  17. # 连接到数据库
  18. cnx = mysql.connector.connect(**config)
  19. cursor = cnx.cursor()
  20. # 执行SQL删除语句
  21. cursor.execute(delete_query, (id_card_to_delete,))
  22. # 提交更改
  23. cnx.commit()
  24. print(f"Record with ID_Card '{id_card_to_delete}' deleted successfully!")
  25. except mysql.connector.Error as err:
  26. print(f"Error: '{err}'")
  27. finally:
  28. # 关闭游标和连接
  29. if cursor:
  30. cursor.close()
  31. if cnx.is_connected():
  32. cnx.close()
2-2、用PyMySQL库
  1. import pymysql
  2. # 数据库连接配置
  3. config = {
  4. 'user': 'root', # 替换为你的MySQL用户名
  5. 'password': '123456', # 替换为你的MySQL密码
  6. 'host': '127.0.0.1', # 如果数据库在远程服务器上,请替换为相应的主机名或IP地址
  7. 'database': 'test_database', # 数据库名
  8. 'charset': 'utf8mb4', # 添加字符集配置,防止编码问题
  9. 'cursorclass': pymysql.cursors.DictCursor # 使用字典游标(虽然在这个删除操作中不是必需的)
  10. }
  11. # 要删除的记录的ID_Card值
  12. id_card_to_delete = '443689564710526448'
  13. # SQL删除语句
  14. delete_query = """
  15. DELETE FROM myelsa_table
  16. WHERE ID_Card = %s
  17. """
  18. try:
  19. # 连接到数据库
  20. cnx = pymysql.connect(**config)
  21. with cnx.cursor() as cursor:
  22. # 使用with语句确保游标在使用完毕后被关闭
  23. # 执行SQL删除语句
  24. cursor.execute(delete_query, (id_card_to_delete,))
  25. # 提交更改
  26. cnx.commit()
  27. print(f"Record with ID_Card '{id_card_to_delete}' deleted successfully!")
  28. except pymysql.Error as err:
  29. print(f"Error: '{err}'")
  30. # 使用with语句连接数据库时,在with块结束后连接将自动关闭
  31. # 如果没有使用with语句,需要显式关闭连接
  32. if cnx.open:
  33. cnx.close()
2-3、用PeeWee库
  1. from peewee import *
  2. # 数据库连接配置
  3. db = MySQLDatabase('test_database', user='root', password='123456', host='127.0.0.1')
  4. # 定义模型,映射到myelsa_table表
  5. class Myelsa_Table(Model):
  6. name = CharField()
  7. ID_Card = CharField(unique=True) # 假设ID_Card是唯一的
  8. age = IntegerField()
  9. city = CharField()
  10. class Meta:
  11. database = db
  12. # 连接到数据库
  13. db.connect()
  14. # 要删除的记录的ID_Card值
  15. id_card_to_delete = '443689564710526448'
  16. try:
  17. # 使用模型来删除记录
  18. query = Myelsa_Table.delete().where(Myelsa_Table.ID_Card == id_card_to_delete)
  19. query.execute()
  20. print(f"Record with ID_Card '{id_card_to_delete}' deleted successfully!")
  21. except Exception as e:
  22. print(f"Error: '{e}'")
  23. finally:
  24. # 关闭数据库连接(Peewee会在连接池中管理连接,通常不需要显式关闭)
  25. # 但如果你确定不再需要连接,可以调用db.close()
  26. # db.close()
  27. pass
  28. # 注意:在实际应用中,通常不需要显式关闭连接,因为Peewee会管理连接池
  29. # 但在某些情况下,例如脚本结束时,你可能想要确保所有资源都被释放
2-4、用SQLAlchemy库
  1. from sqlalchemy import create_engine, Column, Integer, String, MetaData, Table
  2. from sqlalchemy.orm import sessionmaker
  3. from sqlalchemy.exc import SQLAlchemyError
  4. # 数据库连接配置
  5. config = {
  6. 'username': 'root', # 替换为你的MySQL用户名
  7. 'password': '123456', # 替换为你的MySQL密码
  8. 'host': '127.0.0.1', # 如果数据库在远程服务器上,请替换为相应的主机名或IP地址
  9. 'database': 'test_database', # 数据库名
  10. 'port': 3306, # 如果端口不是默认的3306,请添加此行并替换为正确的端口
  11. }
  12. # 创建数据库引擎
  13. engine = create_engine(
  14. f'mysql+pymysql://{config["username"]}:{config["password"]}@{config["host"]}:{config["port"]}/{config["database"]}')
  15. # 要删除的记录的ID_Card值
  16. id_card_to_delete = '443689564710526448'
  17. # 定义元数据(如果使用ORM,则无需此步骤,但这里为简单起见使用Table对象)
  18. metadata = MetaData()
  19. myelsa_table = Table('myelsa_table', metadata, autoload_with=engine)
  20. # 创建会话类
  21. Session = sessionmaker(bind=engine)
  22. try:
  23. # 创建会话对象
  24. session = Session()
  25. # 执行SQL删除语句(这里使用session.execute而不是ORM方法)
  26. session.execute(myelsa_table.delete().where(myelsa_table.c.ID_Card == id_card_to_delete))
  27. # 提交更改
  28. session.commit()
  29. print(f"Record with ID_Card '{id_card_to_delete}' deleted successfully!")
  30. except SQLAlchemyError as e:
  31. print(f"Error: '{e}'")
  32. # 如果出错,回滚更改
  33. session.rollback()
  34. finally:
  35. # 关闭会话
  36. session.close()

3、修改记录

3-1、用mysql-connector-python库
  1. import mysql.connector
  2. # 数据库连接配置
  3. config = {
  4. 'username': 'root', # 替换为你的MySQL用户名
  5. 'password': '123456', # 替换为你的MySQL密码
  6. 'host': '127.0.0.1', # 如果数据库在远程服务器上,请替换为相应的主机名或IP地址
  7. 'database': 'test_database', # 数据库名
  8. }
  9. # 要更新的记录的ID_Card值
  10. id_card_to_update = '443689564710526448'
  11. # 新的记录值
  12. new_values = {
  13. 'name': 'Jimmy',
  14. 'age': 15,
  15. 'city': 'Foshan'
  16. }
  17. # SQL更新语句
  18. update_query = """
  19. UPDATE myelsa_table
  20. SET name = %s, age = %s, city = %s
  21. WHERE ID_Card = %s
  22. """
  23. try:
  24. # 连接到数据库
  25. cnx = mysql.connector.connect(**config)
  26. cursor = cnx.cursor()
  27. # 执行SQL更新语句
  28. cursor.execute(update_query, (new_values['name'], new_values['age'], new_values['city'], id_card_to_update))
  29. # 提交更改
  30. cnx.commit()
  31. print(f"Record with ID_Card '{id_card_to_update}' updated successfully!")
  32. except mysql.connector.Error as err:
  33. print(f"Error: '{err}'")
  34. finally:
  35. # 关闭游标和连接
  36. if cursor:
  37. cursor.close()
  38. if cnx.is_connected():
  39. cnx.close()
3-2、用PyMySQL库
  1. import pymysql
  2. # 数据库连接配置
  3. config = {
  4. 'user': 'root', # 替换为你的MySQL用户名
  5. 'password': '123456', # 替换为你的MySQL密码
  6. 'host': '127.0.0.1', # 如果数据库在远程服务器上,请替换为相应的主机名或IP地址
  7. 'database': 'test_database', # 数据库名
  8. 'charset': 'utf8mb4', # 添加字符集配置,防止编码问题
  9. 'cursorclass': pymysql.cursors.DictCursor # 虽然在更新操作中不是必需的,但这里保持一致
  10. }
  11. # 要更新的记录的ID_Card值
  12. id_card_to_update = '443689564710526448'
  13. # 新的记录值
  14. new_values = {
  15. 'name': 'Jimmy',
  16. 'age': 15,
  17. 'city': 'Foshan'
  18. }
  19. # SQL更新语句
  20. update_query = """
  21. UPDATE myelsa_table
  22. SET name = %s, age = %s, city = %s
  23. WHERE ID_Card = %s
  24. """
  25. try:
  26. # 连接到数据库
  27. cnx = pymysql.connect(**config)
  28. with cnx.cursor() as cursor:
  29. # 使用with语句确保游标在使用完毕后被关闭
  30. # 执行SQL更新语句
  31. cursor.execute(update_query, (new_values['name'], new_values['age'], new_values['city'], id_card_to_update))
  32. # 提交更改
  33. cnx.commit()
  34. print(f"Record with ID_Card '{id_card_to_update}' updated successfully!")
  35. except pymysql.MySQLError as err:
  36. print(f"Error: '{err}'")
  37. finally:
  38. # 使用with语句时,连接会在with块结束时自动关闭
  39. # 如果连接没有通过with管理,需要在这里关闭
  40. if cnx.open:
  41. cnx.close()
3-3、用PeeWee库
  1. from peewee import *
  2. # 定义数据库连接
  3. db = MySQLDatabase('test_database', user='root', password='123456', host='127.0.0.1')
  4. # 定义数据库模型类
  5. class MyElsa_Table(Model):
  6. ID_Card = CharField(primary_key=True) # 注意:这里保留了你的原始字段命名
  7. name = CharField()
  8. age = IntegerField()
  9. city = CharField()
  10. class Meta:
  11. database = db
  12. # 连接到数据库
  13. db.connect()
  14. # 要更新的记录的ID_Card值
  15. id_card_to_update = '443689564710526448'
  16. # 新的记录值
  17. new_values = {
  18. 'name': 'Jimmy',
  19. 'age': 15,
  20. 'city': 'Foshan'
  21. }
  22. try:
  23. # 使用ORM方法执行更新操作
  24. query = (MyElsa_Table
  25. .update(name=new_values['name'], age=new_values['age'], city=new_values['city'])
  26. .where(MyElsa_Table.ID_Card == id_card_to_update))
  27. query.execute()
  28. # 如果没有错误,打印成功消息
  29. print(f"Record with ID_Card '{id_card_to_update}' updated successfully!")
  30. except Exception as e:
  31. # 捕获异常并打印错误信息
  32. print(f"Error: '{e}'")
  33. finally:
  34. # 关闭数据库连接
  35. db.close()
3-4、用SQLAlchemy库
  1. from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
  2. from sqlalchemy.orm import sessionmaker
  3. from sqlalchemy.exc import SQLAlchemyError
  4. # 数据库连接配置
  5. config = {
  6. 'username': 'root', # 替换为你的MySQL用户名
  7. 'password': '123456', # 替换为你的MySQL密码
  8. 'host': '127.0.0.1', # 如果数据库在远程服务器上,请替换为相应的主机名或IP地址
  9. 'database': 'test_database', # 数据库名
  10. 'port': 3306, # 如果端口不是默认的3306,请添加此行并替换为正确的端口
  11. 'echo': False # 如果想看到执行的SQL语句,设置为True
  12. }
  13. # 创建数据库引擎
  14. engine = create_engine(
  15. f'mysql+pymysql://{config["username"]}:{config["password"]}@{config["host"]}:{config["port"]}/{config["database"]}',
  16. echo=config['echo'])
  17. # 定义元数据
  18. metadata = MetaData()
  19. # 假设你的表结构如下(需要根据实际情况调整列类型和名称)
  20. myelsa_table = Table('myelsa_table', metadata,
  21. Column('ID_Card', String, primary_key=True),
  22. Column('name', String),
  23. Column('age', Integer),
  24. Column('city', String),
  25. autoload_with=engine
  26. )
  27. # 要更新的记录的ID_Card值
  28. id_card_to_update = '443689564710526448'
  29. # 新的记录值
  30. new_values = {
  31. 'name': 'Jimmy',
  32. 'age': 15,
  33. 'city': 'Foshan'
  34. }
  35. # 创建会话类
  36. Session = sessionmaker(bind=engine)
  37. try:
  38. # 创建会话对象
  39. session = Session()
  40. # 构造更新语句
  41. stmt = myelsa_table.update().where(myelsa_table.c.ID_Card == id_card_to_update).values(**new_values)
  42. # 执行更新
  43. session.execute(stmt)
  44. # 提交更改
  45. session.commit()
  46. print(f"Record with ID_Card '{id_card_to_update}' updated successfully!")
  47. except SQLAlchemyError as e:
  48. print(f"Error: '{e}'")
  49. # 如果出错,回滚更改
  50. session.rollback()
  51. finally:
  52. # 关闭会话
  53. session.close()

4、查询记录

4-1、用mysql-connector-python库
  1. import mysql.connector
  2. # 数据库连接配置
  3. config = {
  4. 'username': 'root', # 替换为你的MySQL用户名
  5. 'password': '123456', # 替换为你的MySQL密码
  6. 'host': '127.0.0.1', # 如果数据库在远程服务器上,请替换为相应的主机名或IP地址
  7. 'database': 'test_database', # 数据库名
  8. }
  9. # 查询所有记录的SQL语句
  10. query_all = """
  11. SELECT * FROM myelsa_table
  12. """
  13. # 查询特定记录的SQL语句(例如,根据ID_Card查询)
  14. id_card_to_query = '443689564710526448'
  15. query_by_id_card = """
  16. SELECT * FROM myelsa_table WHERE ID_Card = %s
  17. """
  18. try:
  19. # 连接到数据库
  20. cnx = mysql.connector.connect(**config)
  21. cursor = cnx.cursor()
  22. # 执行查询所有记录的SQL语句
  23. cursor.execute(query_all)
  24. # 获取所有记录
  25. for (name, id_card, age, city) in cursor:
  26. print(f"Name: {name}, ID Card: {id_card}, Age: {age}, City: {city}")
  27. # 如果需要查询特定记录,取消注释以下代码
  28. # cursor.execute(query_by_id_card, (id_card_to_query,))
  29. # record = cursor.fetchone()
  30. # if record:
  31. # (name, id_card, age, city) = record
  32. # print(f"Name: {name}, ID Card: {id_card}, Age: {age}, City: {city}")
  33. # else:
  34. # print(f"No record found for ID Card: {id_card_to_query}")
  35. except mysql.connector.Error as err:
  36. print(f"Error: '{err}'")
  37. finally:
  38. # 关闭游标和连接
  39. if cursor:
  40. cursor.close()
  41. if cnx.is_connected():
  42. cnx.close()
4-2、用PyMySQL库
  1. import pymysql
  2. # 数据库连接配置
  3. config = {
  4. 'user': 'root', # 替换为你的MySQL用户名
  5. 'password': '123456', # 替换为你的MySQL密码
  6. 'host': '127.0.0.1', # 如果数据库在远程服务器上,请替换为相应的主机名或IP地址
  7. 'database': 'test_database', # 数据库名
  8. 'charset': 'utf8mb4', # 添加字符集配置,防止编码问题
  9. 'cursorclass': pymysql.cursors.DictCursor # 使用字典游标以便按列名访问数据
  10. }
  11. # 查询所有记录的SQL语句
  12. query_all = """
  13. SELECT * FROM myelsa_table
  14. """
  15. # 查询特定记录的SQL语句(例如,根据ID_Card查询)
  16. id_card_to_query = '443689564710526448'
  17. query_by_id_card = """
  18. SELECT * FROM myelsa_table WHERE ID_Card = %s
  19. """
  20. try:
  21. # 连接到数据库
  22. cnx = pymysql.connect(**config)
  23. with cnx.cursor(pymysql.cursors.DictCursor) as cursor: # 使用with语句自动管理游标
  24. # 执行查询所有记录的SQL语句
  25. cursor.execute(query_all)
  26. # 获取所有记录
  27. for row in cursor:
  28. print(f"Name: {row['name']}, ID Card: {row['ID_Card']}, Age: {row['age']}, City: {row['city']}")
  29. # 如果需要查询特定记录,取消注释以下代码
  30. # cursor.execute(query_by_id_card, (id_card_to_query,))
  31. # record = cursor.fetchone()
  32. # if record:
  33. # print(f"Name: {record['name']}, ID Card: {record['ID_Card']}, Age: {record['age']}, City: {record['city']}")
  34. # else:
  35. # print(f"No record found for ID Card: {id_card_to_query}")
  36. # 注意:因为使用了with语句,所以不需要显式关闭游标
  37. # 提交(在这里其实不需要,因为只是查询)
  38. cnx.commit()
  39. except pymysql.MySQLError as err:
  40. print(f"Error: '{err}'")
  41. finally:
  42. # 使用with语句时,连接会在with块结束时自动关闭
  43. # 如果连接没有通过with管理,需要在这里关闭
  44. if cnx.open:
  45. cnx.close()
4-3、用PeeWee库
  1. from peewee import *
  2. # 数据库连接配置
  3. db = MySQLDatabase('test_database', user='root', password='123456', host='127.0.0.1')
  4. # 定义数据库模型类
  5. class MyElsa_Table(Model):
  6. ID_Card = CharField(primary_key=True)
  7. name = CharField()
  8. age = IntegerField()
  9. city = CharField()
  10. class Meta:
  11. database = db
  12. # 连接到数据库
  13. db.connect()
  14. # 查询所有记录
  15. def query_all_records():
  16. for record in MyElsa_Table.select():
  17. print(f"Name: {record.name}, ID Card: {record.ID_Card}, Age: {record.age}, City: {record.city}")
  18. # 查询特定记录(根据ID_Card)
  19. def query_record_by_id_card(id_card):
  20. record = MyElsa_Table.get_or_none(MyElsa_Table.ID_Card == id_card)
  21. if record:
  22. print(f"Name: {record.name}, ID Card: {record.ID_Card}, Age: {record.age}, City: {record.city}")
  23. else:
  24. print(f"No record found for ID Card: {id_card}")
  25. # ID_Card要查询的特定值
  26. id_card_to_query = '443689564710526448'
  27. try:
  28. # 查询所有记录
  29. query_all_records()
  30. print("\n---\n")
  31. # 查询特定记录
  32. query_record_by_id_card(id_card_to_query)
  33. except MyElsa_Table.DoesNotExist:
  34. print(f"No record found for ID Card: {id_card_to_query}")
  35. except Exception as e:
  36. print(f"Error: '{e}'")
  37. finally:
  38. # 关闭数据库连接(如果使用了连接池,则可能不需要显式关闭)
  39. db.close()
4-4、用SQLAlchemy库
  1. from sqlalchemy import create_engine, Column, Integer, String, MetaData
  2. from sqlalchemy.orm import sessionmaker
  3. from sqlalchemy.ext.declarative import declarative_base
  4. from sqlalchemy.exc import SQLAlchemyError
  5. # 声明基础类
  6. Base = declarative_base()
  7. # 定义ORM模型
  8. class MyElsaTable(Base):
  9. __tablename__ = 'myelsa_table'
  10. id_card = Column(String, primary_key=True)
  11. name = Column(String)
  12. age = Column(Integer)
  13. city = Column(String)
  14. # 数据库连接配置
  15. config = {
  16. 'username': 'root', # 替换为你的MySQL用户名
  17. 'password': '123456', # 替换为你的MySQL密码
  18. 'host': '127.0.0.1', # 如果数据库在远程服务器上,请替换为相应的主机名或IP地址
  19. 'database': 'test_database', # 数据库名
  20. 'port': 3306, # 端口号,默认为3306
  21. 'echo': False # 是否打印SQL语句
  22. }
  23. # 创建数据库引擎
  24. engine = create_engine(
  25. f'mysql+pymysql://{config["username"]}:{config["password"]}@{config["host"]}:{config["port"]}/{config["database"]}',
  26. echo=config['echo'])
  27. # 创建Session类
  28. Session = sessionmaker(bind=engine)
  29. try:
  30. # 创建Session对象
  31. session = Session()
  32. # 查询所有记录
  33. all_records = session.query(MyElsaTable).all()
  34. for record in all_records:
  35. print(f"Name: {record.name}, ID Card: {record.id_card}, Age: {record.age}, City: {record.city}")
  36. # 查询特定记录(例如,根据ID_Card查询)
  37. id_card_to_query = '443689564710526448'
  38. record = session.query(MyElsaTable).filter_by(id_card=id_card_to_query).first()
  39. if record:
  40. print(f"Name: {record.name}, ID Card: {record.id_card}, Age: {record.age}, City: {record.city}")
  41. else:
  42. print(f"No record found for ID Card: {id_card_to_query}")
  43. except SQLAlchemyError as e:
  44. print(f"Error: '{e}'")
  45. finally:
  46. # 关闭Session
  47. session.close()

二、推荐阅读

1、Python函数之旅

2、Python算法之旅

3、博客个人主页

遨游码海,我心飞扬
微信名片
注:本文转载自blog.csdn.net的神奇夜光杯的文章"https://myelsa1024.blog.csdn.net/article/details/139188631"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2024 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top