數據庫是存儲在計算機系統中的結構化信息或數據的組織良好的集合。在數據庫中,數據以表格的形式排列,我們可以通過查詢來訪問這些信息或數據。
Python 可以用來連接數據庫。 MySQL 是最受歡迎的數據庫之一。在本教程中,我們將學習通過 Python 建立與 MySQL 的連接。讓我們理解使用 Python 使用 MySQL 的以下步驟。
- 安裝 MySQL 驅動程序
- 創建連接對象
- 創建光標對象
- 執行查詢
安裝 MySQL 驅動程序
首先,我們的系統中需要一個 MySQL 驅動程序。安裝 MySQL 軟件,配置設置。我們將使用 MySQL 連接器驅動程序,它是使用 pip 命令安裝的。打開命令提示符並鍵入以下命令。
python -m pip install mysql-connector-python
按回車鍵。它將下載 MySQL 驅動程序。
- 驗證驅動程序
讓我們檢查一下是否安裝正確。這可以通過導入 mysql.connector 來完成。
import mysql.connector
如果這一行執行沒有錯誤,說明 MySQL 連接器安裝正確。我們準備使用它。
創建連接對象
mysql.connector 提供了 connect() 方法,用於在 mysql 數據庫和 Python 應用之間創建連接。語法如下。
語法:
Conn_obj= mysql.connector.connect(host = <hostname>, user = <username>, passwd = <password>)
connect()函數接受以下參數。
- 主機名- 表示運行 MySQL 的服務器名稱或 IP 地址。
- Username – 它代表我們使用 MySQL 服務器的用戶名。默認情況下,MySQL 數據庫的用戶名是 root。
- 密碼- 密碼在安裝 MySQL 數據庫時提供。如果我們使用根目錄,我們不需要傳遞密碼。
- 數據庫- 指定我們要連接的數據庫名稱。當我們有多個數據庫時,使用這個參數。
考慮下面的例子。
示例-
import mysql.connector
# Creating a the connection object
conn_obj = mysql.connector.connect(host="localhost", user="root", passwd="admin123")
# printing the connection object
print(conn_obj)
輸出:
<mysql.connector.connection.MySQLConnection object at 0x7fb142edd780>
創建光標對象
需要創建連接對象,因為它為多個工作環境提供了到數據庫的相同連接。光標()功能用於創建光標對象。它是執行 SQL 查詢的入口。語法如下。
語法:
Con_obj = conn.cursor()
讓我們理解下面的例子。
示例-
import mysql.connector
# Creating the connection object
conn_obj = mysql.connector.connect(host="localhost", user="root", passwd="admin123", database="mydatabase")
# printing the connection object
print(conn_obj)
# creating the cursor object
cur_obj = conn_obj.cursor()
print(cur_obj)
輸出:
MySQLCursor: (Nothing executed yet)
執行查詢
在下面的示例中,我們將通過執行查詢來創建一個數據庫。讓我們理解下面的例子。
示例-
import mysql.connector
# Creating the connection object
conn_obj = mysql.connector.connect(host="localhost", user="root", passwd="admin123")
# creating the cursor object
cur_obj = conn_obj.cursor()
try:
# creating a new database using query
cur_obj.execute("create database New_PythonDB")
# getting the list of all the databases which will now include the new database New_PythonDB
dbms = cur_obj.execute("show databases")
except:
conn_obj.rollback() # it is used if the operation is failed then it will not reflect in your database
for x in cur_obj:
print(x)
conn_obj.close()
輸出:
'information_schema',)
('javatpoint',)
('javatpoint1',)
(New_Pythondb)
('mydb',)
('mydb1',)
('mysql',)
('performance_schema',)
('testDB',)
在上面的教程中,我們已經討論了如何通過 Python 建立到 MySQL 的連接。可以從(https://www.javatpoint.com/python-mysql-database-connection)用 MySQL 學習完整的 Python。
原創文章,作者:EKYWN,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/130611.html