Python数据库连接怎么实现

发布时间:2025-04-18 00:02:58 作者:小樊
来源:亿速云 阅读:83

在Python中,连接数据库通常需要使用特定的数据库适配器或驱动程序。以下是一些常见数据库的连接方法:

  1. SQLite: SQLite是一个轻量级的数据库,不需要单独的服务器进程。Python标准库中的sqlite3模块提供了对SQLite数据库的支持。

    import sqlite3
    
    # 连接到SQLite数据库(如果不存在,则会自动创建)
    conn = sqlite3.connect('example.db')
    
    # 创建一个Cursor对象使用cursor()方法
    cursor = conn.cursor()
    
    # 执行SQL查询
    cursor.execute('''CREATE TABLE IF NOT EXISTS stocks
                      (date text, trans text, symbol text, qty real, price real)''')
    
    # 提交事务
    conn.commit()
    
    # 关闭Cursor和连接
    cursor.close()
    conn.close()
    
  2. MySQL: 对于MySQL数据库,可以使用mysql-connector-pythonpymysql等第三方库。

    使用mysql-connector-python:

    import mysql.connector
    
    # 连接到MySQL数据库
    conn = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword",
        database="yourdatabase"
    )
    
    # 创建一个Cursor对象
    cursor = conn.cursor()
    
    # 执行SQL查询
    cursor.execute("SELECT * FROM your_table")
    
    # 获取查询结果
    for row in cursor.fetchall():
        print(row)
    
    # 关闭Cursor和连接
    cursor.close()
    conn.close()
    
  3. PostgreSQL: 对于PostgreSQL数据库,可以使用psycopg2库。

    import psycopg2
    
    # 连接到PostgreSQL数据库
    conn = psycopg2.connect(
        dbname="yourdatabase",
        user="yourusername",
        password="yourpassword",
        host="localhost"
    )
    
    # 创建一个Cursor对象
    cursor = conn.cursor()
    
    # 执行SQL查询
    cursor.execute("SELECT version();")
    
    # 获取查询结果
    db_version = cursor.fetchone()
    print(db_version)
    
    # 关闭Cursor和连接
    cursor.close()
    conn.close()
    
  4. MongoDB: 对于NoSQL数据库如MongoDB,可以使用pymongo库。

    from pymongo import MongoClient
    
    # 创建MongoClient对象
    client = MongoClient('mongodb://localhost:27017/')
    
    # 获取数据库
    db = client['yourdatabase']
    
    # 获取集合
    collection = db['yourcollection']
    
    # 插入文档
    post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"]}
    post_id = collection.insert_one(post).inserted_id
    
    # 查询文档
    for post in collection.find():
        print(post)
    

在连接数据库时,请确保已经安装了相应的库,并且数据库服务器正在运行。此外,为了安全起见,不要在代码中硬编码数据库的用户名和密码,而应该使用环境变量或其他安全的方式来管理这些敏感信息。

推荐阅读:
  1. python连接数据库
  2. ubunt18.04LTS+vscode+anaconda3下的python+C++调试方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:Python Web开发框架推荐

下一篇:键值存储如何扩展存储容量

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》