以下是在Ubuntu上使用Python连接不同数据库的教程:
pip install mysql-connector-python。sudo apt update,sudo apt install mysql-server,然后运行sudo mysql_secure_installation进行安全设置。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()
pip install psycopg2。sudo apt update,sudo apt install postgresql postgresql-contrib。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()
sqlite3模块,无需额外安装。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()
pip install pymongo。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