在Ubuntu上使用Python連接數據庫,通常需要使用相應的數據庫驅動程序。以下是一些常見數據庫的連接方法:
安裝MySQL客戶端庫:
sudo apt-get update
sudo apt-get install python3-mysqldb
Python代碼示例:
import mysql.connector
# 連接數據庫
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 創建游標對象
mycursor = mydb.cursor()
# 執行SQL查詢
mycursor.execute("SELECT * FROM yourtable")
# 獲取查詢結果
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# 關閉連接
mydb.close()
安裝PostgreSQL客戶端庫:
sudo apt-get update
sudo apt-get install python3-psycopg2
Python代碼示例:
import psycopg2
# 連接數據庫
conn = psycopg2.connect(
dbname="yourdatabase",
user="yourusername",
password="yourpassword",
host="localhost"
)
# 創建游標對象
cur = conn.cursor()
# 執行SQL查詢
cur.execute("SELECT * FROM yourtable")
# 獲取查詢結果
rows = cur.fetchall()
for row in rows:
print(row)
# 關閉游標和連接
cur.close()
conn.close()
Python代碼示例:
import sqlite3
# 連接數據庫
conn = sqlite3.connect('yourdatabase.db')
# 創建游標對象
cursor = conn.cursor()
# 執行SQL查詢
cursor.execute("SELECT * FROM yourtable")
# 獲取查詢結果
rows = cursor.fetchall()
for row in rows:
print(row)
# 關閉游標和連接
cursor.close()
conn.close()
安裝MongoDB客戶端庫:
sudo apt-get update
sudo apt-get install python3-pymongo
Python代碼示例:
from pymongo import MongoClient
# 連接MongoDB
client = MongoClient('mongodb://localhost:27017/')
# 選擇數據庫
db = client['yourdatabase']
# 選擇集合
collection = db['yourcollection']
# 查詢文檔
documents = collection.find()
for doc in documents:
print(doc)
# 關閉連接
client.close()
通過以上步驟,你可以在Ubuntu上使用Python連接到不同的數據庫并進行操作。