ubuntu

Ubuntu Python数据库连接教程

小樊
49
2025-09-06 19:25:21
栏目: 编程语言

以下是在Ubuntu上使用Python连接不同数据库的教程:

连接MySQL数据库

import mysql.connector

try:
    connection = mysql.connector.connect(
        host='localhost',
        user='your_username',
        password='your_password',
        database='your_database'
    )
    if connection.is_connected():
        cursor = connection.cursor()
        cursor.execute("SELECT * FROM your_table")
        result = cursor.fetchall()
        for row in result:
            print(row)
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()

连接PostgreSQL数据库

import psycopg2

try:
    connection = psycopg2.connect(
        dbname='your_database',
        user='your_username',
        password='your_password',
        host='localhost'
    )
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM your_table")
    rows = cursor.fetchall()
    for row in rows:
        print(row)
finally:
    if connection:
        cursor.close()
        connection.close()

连接SQLite数据库

import sqlite3

connection = sqlite3.connect('your_database.db')
cursor = connection.cursor()
cursor.execute("SELECT * FROM your_table")
rows = cursor.fetchall()
for row in rows:
    print(row)
cursor.close()
connection.close()

连接MongoDB数据库

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
db = client['your_database']
collection = db['your_collection']
documents = collection.find()
for document in documents:
    print(document)
client.close

0
看了该问题的人还看了