在CentOS上使用Python連接數據庫,通常需要以下幾個步驟:
安裝數據庫:首先,你需要在CentOS上安裝一個數據庫。這里以MySQL為例。
安裝Python數據庫驅動:根據你要連接的數據庫類型,安裝相應的Python驅動。對于MySQL,你可以使用mysql-connector-python
或PyMySQL
。
編寫Python代碼:使用Python數據庫驅動編寫代碼來連接數據庫。
下面是具體的操作步驟:
步驟1:安裝MySQL
在CentOS上安裝MySQL,可以使用以下命令:
sudo yum install mysql-server
啟動MySQL服務:
sudo systemctl start mysqld
設置MySQL開機自啟:
sudo systemctl enable mysqld
運行安全設置腳本,設置root密碼等:
sudo mysql_secure_installation
步驟2:安裝Python數據庫驅動
使用pip安裝mysql-connector-python
:
pip install mysql-connector-python
或者安裝PyMySQL
:
pip install pymysql
步驟3:編寫Python代碼
創建一個名為connect_db.py
的文件,并編寫以下代碼:
使用mysql-connector-python
:
import mysql.connector
# 連接數據庫
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
# 創建游標
cursor = cnx.cursor()
# 執行SQL查詢
query = "SELECT * FROM your_table"
cursor.execute(query)
# 獲取查詢結果
result = cursor.fetchall()
for row in result:
print(row)
# 關閉游標和連接
cursor.close()
cnx.close()
使用PyMySQL
:
import pymysql
# 連接數據庫
cnx = pymysql.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
# 創建游標
cursor = cnx.cursor()
# 執行SQL查詢
query = "SELECT * FROM your_table"
cursor.execute(query)
# 獲取查詢結果
result = cursor.fetchall()
for row in result:
print(row)
# 關閉游標和連接
cursor.close()
cnx.close()
將your_username
、your_password
、your_database
和your_table
替換為實際的值,然后運行connect_db.py
文件:
python connect_db.py
這樣,你就可以在CentOS上使用Python連接數據庫并執行SQL查詢了。