在Ubuntu系统中,Python可以通过多种方式连接到数据库。以下是一些常见的数据库和相应的连接方法:
SQLite:
SQLite是一个轻量级的数据库,它不需要一个单独的服务器进程。Python通过内置的sqlite3模块来连接SQLite数据库。
import sqlite3
conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()
# 执行SQL语句...
conn.close()
MySQL/MariaDB:
对于MySQL或MariaDB数据库,你可以使用mysql-connector-python或pymysql这样的第三方库。
使用mysql-connector-python:
import mysql.connector
from mysql.connector import Error
try:
conn = mysql.connector.connect(
host='localhost',
database='my_database',
user='username',
password='password'
)
if conn.is_connected():
db_Info = conn.get_server_info()
print("Connected to MySQL Database version ", db_Info)
cursor = conn.cursor()
# 执行SQL语句...
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if conn.is_connected():
cursor.close()
conn.close()
print("MySQL connection is closed")
使用pymysql:
import pymysql
conn = pymysql.connect(host='localhost', user='username', password='password', db='my_database')
cursor = conn.cursor()
# 执行SQL语句...
conn.close()
PostgreSQL:
对于PostgreSQL数据库,你可以使用psycopg2库。
import psycopg2
from psycopg2 import OperationalError
try:
conn = psycopg2.connect(
dbname="my_database",
user="username",
password="password",
host="localhost"
)
cursor = conn.cursor()
# 执行SQL语句...
except OperationalError as e:
print(f"The error '{e}' occurred")
finally:
if conn is not None:
cursor.close()
conn.close()
print("Database connection closed.")
MongoDB:
对于MongoDB,你可以使用pymongo库。
from pymongo import MongoClient
client = MongoClient('mongodb://username:password@localhost:27017/')
db = client['my_database']
collection = db['my_collection']
# 执行数据库操作...
在安装这些库时,你可能需要使用pip,例如:
pip install mysql-connector-python
# 或者
pip install pymysql
# 或者
pip install psycopg2-binary
# 或者
pip install pymongo
请确保在尝试连接数据库之前,数据库服务已经在运行,并且你已经创建了相应的数据库和用户权限。此外,根据你的数据库配置,可能需要安装额外的数据库服务器软件(如MySQL Server、PostgreSQL等)。