Python-链接数据库

105 阅读1分钟

连接关系型数据库(MySQL)示例

  • 使用 pymysql 库连接 MySQL 数据库

import pymysql

# 建立数据库连接
connection = pymysql.connect(
    host='localhost',
    user='username',
    password='password',
    db='database_name',
    charset='utf8mb4',
    cursorclass=pymysql.cursors.DictCursor
)

try:
    # 创建一个游标对象
    with connection.cursor() as cursor:
        # 执行 SQL 查询
        sql = "SELECT * FROM table_name"
        cursor.execute(sql)
        result = cursor.fetchall()
        for row in result:
            print(row)
finally:
    # 关闭数据库连接
    connection.close()

连接非关系型数据库(MongoDB)示例

  • 使用 pymongo 库连接 MongoDB 数据库

  • python

  • Copy code

  • from pymongo import MongoClient

建立数据库连接

client = MongoClient('mongodb://localhost:27017/')

# 选择数据库
db = client['database_name']

# 选择集合(表)
collection = db['collection_name']

# 查询文档
query = {'key': 'value'}
result = collection.find(query)
for document in result:
    print(document)