在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等)。
以上就是关于“Ubuntu系统里Python如何连接数据库”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm