本文将以SQLite、MySQL,PostgreSQL為例講解python怎樣連接配接遠端資料庫并執行相關資料庫操作。
SQLite
SQLite可能是與Python連接配接的最友善的資料庫,因為我們不需要安裝任何外部Python SQL子產品即可使用。預設情況下,Python會自帶一個名為
sqlite3的Python SQL庫
,我們可以使用該庫與SQLite資料庫進行互動。而且,我們甚至不需要安裝和運作SQLite伺服器即可執行資料庫操作!
下面是使用
sqlite3
連接配接到SQLite資料庫的方法,看代碼就行 ,關鍵位置都給了注釋
#導入相關子產品
import sqlite3
from sqlite3 import Error
def create_connection(path):
connection = None
try:
#使用.connect()連接配接,并将SQLite資料庫路徑作為參數。如果資料庫位于指定位置,則建立與資料庫的連接配接。否則,将在指定位置建立一個新資料庫,并建立連接配接。
connection = sqlite3.connect(path)
print("成功連接配接")
except Error as e:
print(f"錯誤 '{e}' 發生")
return connection
複制
connect(path)傳回一個連接配接對象,該對象由create_connection()傳回。此連接配接對象可用于在SQLite資料庫上執行查詢。接下來執行下面的指令就可以連接配接到資料庫
connection = create_connection("填寫你的路徑\filename.sqlite")
複制
執行完畢後會在目錄下面看到多了一個以.sqlite結尾的檔案。
MySQL
與SQLite不同,沒有預設的Python SQL子產品可用于連接配接到MySQL資料庫。相反,我們需要安裝mysql-connector-python以便從Python應用程式中與MySQL資料庫進行互動。
pip install mysql-connector-python
但是需要注意,MySQL是基于伺服器的資料庫管理系統。一台MySQL伺服器可以有多個資料庫。與SQLite不同,在SQLite中建立連接配接等同于建立資料庫,MySQL資料庫兩步來建立資料庫:首先與MySQL伺服器建立連接配接,然後執行一個單獨的查詢來建立資料庫。
import mysql.connector
from mysql.connector import Error
def create_connection(host_name, user_name, user_password):
connection = None
try:
#建立連接配接
connection = mysql.connector.connect(
host=host_name,
user=user_name,
passwd=user_password
)
print("連接配接成功")
except Error as e:
print(f"錯誤 '{e}' 發生")
return connection
connection = create_connection("localhost", "root", "")
複制
但是到目前為止,我們僅僅連接配接成功到mysql,并沒有建立database,是以我們定義另一個create_database()接受兩個參數的函數:connection是connection要與之互動的資料庫伺服器的對象。query 是建立資料庫的查詢。
def create_database(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
print("Database created successfully")
except Error as e:
print(f"The error '{e}' occurred")
複制
要執行查詢,我們可以使用cursor對象。将query要執行傳遞給cursor.execute()
create_database_query = "CREATE DATABASE zaoqi" #建立database
create_database(connection, create_database_query)
複制
至此,我們就已經在資料庫伺服器上建立了一個資料庫。
PostgreSQL
與MySQL一樣,沒有預設的Python SQL庫可用于與PostgreSQL資料庫進行互動。是以需要安裝第三方Python SQL驅動程式才能與PostgreSQL互動。納悶我們選擇的驅動程式是psycopg2。
pip install psycopg2
與SQLite和MySQL資料庫一樣,我們定義create_connection()與PostgreSQL資料庫建立連接配接:
import psycopg2
from psycopg2 import OperationalError
def create_connection(db_name, db_user, db_password, db_host, db_port):
connection = None
try:
connection = psycopg2.connect(
database=db_name,
user=db_user,
password=db_password,
host=db_host,
port=db_port,
)
print("Connection to PostgreSQL DB successful")
except OperationalError as e:
print(f"The error '{e}' occurred")
return connection
複制
接下來使用和mysql一樣的辦法建立一個database
def create_database(connection, query):
connection.autocommit = True
cursor = connection.cursor()
try:
cursor.execute(query)
print("Query executed successfully")
except OperationalError as e:
print(f"The error '{e}' occurred")
create_database_query = "CREATE DATABASE zaoqi"
create_database(connection, create_database_query)
複制
至此我們已經學會如何用python連接配接資料庫并建立database,而其他的操作比如增删改查就可以類比得到。