共計 1040 個字符,預計需要花費 3 分鐘才能閱讀完成。
Python 連接數據庫的方法有多種,可以使用標準庫中的 sqlite3 模塊連接 SQLite 數據庫,也可以使用第三方庫如 MySQLdb、psycopg2 等連接 MySQL 或 PostgreSQL 數據庫。以下是連接 MySQL、PostgreSQL 和 SQLite 數據庫的示例代碼:
- 連接 MySQL 數據庫:
import MySQLdb
# 連接數據庫
conn = MySQLdb.connect(host='localhost', user='username', passwd='password', db='database_name')
# 獲取游標
cursor = conn.cursor()
# 執行 SQL 查詢
cursor.execute('SELECT * FROM table_name')
# 獲取查詢結果
results = cursor.fetchall()
# 關閉連接
cursor.close()
conn.close()
- 連接 PostgreSQL 數據庫:
import psycopg2
# 連接數據庫
conn = psycopg2.connect(host='localhost', user='username', password='password', dbname='database_name')
# 獲取游標
cursor = conn.cursor()
# 執行 SQL 查詢
cursor.execute('SELECT * FROM table_name')
# 獲取查詢結果
results = cursor.fetchall()
# 關閉連接
cursor.close()
conn.close()
- 連接 SQLite 數據庫:
import sqlite3
# 連接數據庫
conn = sqlite3.connect('database.db')
# 獲取游標
cursor = conn.cursor()
# 執行 SQL 查詢
cursor.execute('SELECT * FROM table_name')
# 獲取查詢結果
results = cursor.fetchall()
# 關閉連接
cursor.close()
conn.close()
這些示例代碼中,首先使用相應的庫連接數據庫,然后獲取游標進行 SQL 查詢,最后關閉連接。
丸趣 TV 網 – 提供最優質的資源集合!
正文完