linux

Linux中Python如何连接数据库

小樊
41
2025-09-16 13:19:15
栏目: 编程语言

在Linux系统中,Python可以通过多种方式连接到数据库。以下是一些常见的数据库和相应的Python库:

  1. MySQL/MariaDB: 使用mysql-connector-pythonPyMySQL库。 安装:pip install mysql-connector-pythonpip install pymysql 示例代码(使用mysql-connector-python):

    import mysql.connector
    
    cnx = mysql.connector.connect(user='username', password='password',
                                  host='localhost',
                                  database='mydatabase')
    cursor = cnx.cursor()
    
    query = ("SELECT * FROM mytable")
    cursor.execute(query)
    
    for row in cursor:
        print(row)
    
    cursor.close()
    cnx.close()
    
  2. PostgreSQL: 使用psycopg2库。 安装:pip install psycopg2pip install psycopg2-binary 示例代码:

    import psycopg2
    
    conn = psycopg2.connect(dbname="mydatabase", user="username",
                            password="password", host="localhost")
    cur = conn.cursor()
    
    cur.execute("SELECT * FROM mytable;")
    rows = cur.fetchall()
    
    for row in rows:
        print(row)
    
    cur.close()
    conn.close()
    
  3. SQLite: 使用sqlite3库,它是Python标准库的一部分。 示例代码:

    import sqlite3
    
    conn = sqlite3.connect('mydatabase.db')
    cursor = conn.cursor()
    
    cursor.execute("SELECT * FROM mytable")
    rows = cursor.fetchall()
    
    for row in rows:
        print(row)
    
    cursor.close()
    conn.close()
    
  4. MongoDB: 使用pymongo库。 安装:pip install pymongo 示例代码:

    from pymongo import MongoClient
    
    client = MongoClient('mongodb://localhost:27017/')
    db = client['mydatabase']
    collection = db['mytable']
    
    for document in collection.find():
        print(document)
    
  5. Redis: 使用redis-py库。 安装:pip install redis 示例代码:

    import redis
    
    r = redis.Redis(host='localhost', port=6379, db=0)
    
    r.set('mykey', 'Hello, Redis!')
    value = r.get('mykey')
    
    print(value)
    

根据您使用的数据库类型,选择一个合适的库并按照示例代码进行操作。注意替换示例代码中的数据库连接信息(如用户名、密码、主机名和数据库名)以满足您的实际需求。

0
看了该问题的人还看了