在Ubuntu上使用Python連接數據庫,通常需要安裝相應的數據庫驅動程序。以下是一些常見數據庫的連接方法:
首先,確保你已經安裝了MySQL服務器。然后,使用pip安裝mysql-connector-python
或PyMySQL
庫。
pip install mysql-connector-python
或者
pip install PyMySQL
mysql-connector-python
連接MySQLimport mysql.connector
# 連接到MySQL數據庫
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)
PyMySQL
連接MySQLimport pymysql
# 連接到MySQL數據庫
conn = pymysql.connect(
host='localhost',
user='yourusername',
password='yourpassword',
db='yourdatabase'
)
# 創建一個游標對象
cursor = conn.cursor()
# 執行SQL查詢
cursor.execute("SELECT * FROM yourtable")
# 獲取查詢結果
results = cursor.fetchall()
for row in results:
print(row)
首先,確保你已經安裝了PostgreSQL服務器。然后,使用pip安裝psycopg2
庫。
pip install psycopg2
psycopg2
連接PostgreSQLimport psycopg2
# 連接到PostgreSQL數據庫
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)
SQLite是一個嵌入式數據庫,不需要單獨的服務器進程。使用Python內置的sqlite3
模塊即可連接。
import sqlite3
# 連接到SQLite數據庫
conn = sqlite3.connect('yourdatabase.db')
# 創建一個游標對象
cursor = conn.cursor()
# 執行SQL查詢
cursor.execute("SELECT * FROM yourtable")
# 獲取查詢結果
rows = cursor.fetchall()
for row in rows:
print(row)
通過以上步驟,你可以在Ubuntu上使用Python連接并操作數據庫。