在Ubuntu上使用Python连接数据库,通常会使用一些流行的数据库驱动程序。以下是一些常见数据库的连接方法:
MySQL/MariaDB:
mysql-connector-python或pymysql库。pip install mysql-connector-python 或 pip install pymysqlmysql-connector-python):import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
PostgreSQL:
psycopg2库。pip install psycopg2-binaryimport psycopg2
conn = psycopg2.connect(
dbname="yourdatabase",
user="yourusername",
password="yourpassword",
host="127.0.0.1",
port="5432"
)
cur = conn.cursor()
cur.execute('SELECT * FROM your_table_name;')
rows = cur.fetchall()
for row in rows:
print(row)
SQLite:
import sqlite3
conn = sqlite3.connect('yourdatabase.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM your_table_name")
rows = cursor.fetchall()
for row in rows:
print(row)
MongoDB:
pymongo库。pip install pymongofrom pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['yourdatabase']
collection = db['yourcollection']
for document in collection.find():
print(document)
在连接数据库时,请确保替换示例代码中的yourusername, yourpassword, yourdatabase, your_table_name, 和其他占位符为您自己的数据库信息。同时,确保您的数据库服务正在运行,并且可以从您的Python环境中访问。