在Ubuntu下,Python可以通过多种方式连接到数据库。以下是一些常见的数据库和相应的连接方法:
-
MySQL/MariaDB:
要在Python中连接到MySQL或MariaDB数据库,可以使用
mysql-connector-python库。首先,使用以下命令安装它:pip install mysql-connector-python然后,使用以下代码连接到数据库:
import mysql.connector cnx = mysql.connector.connect( host="your_host", user="your_user", password="your_password", database="your_database" ) cursor = cnx.cursor() # Your code to interact with the database goes here cursor.close() cnx.close() -
PostgreSQL:
要在Python中连接到PostgreSQL数据库,可以使用
psycopg2库。首先,使用以下命令安装它:pip install psycopg2然后,使用以下代码连接到数据库:
import psycopg2 cnx = psycopg2.connect( dbname="your_database", user="your_user", password="your_password", host="your_host", port="your_port" ) cursor = cnx.cursor() # Your code to interact with the database goes here cursor.close() cnx.close() -
SQLite:
要在Python中连接到SQLite数据库,可以使用内置的
sqlite3库。使用以下代码连接到数据库:import sqlite3 cnx = sqlite3.connect("your_database.db") cursor = cnx.cursor() # Your code to interact with the database goes here cursor.close() cnx.close() -
MongoDB:
要在Python中连接到MongoDB数据库,可以使用
pymongo库。首先,使用以下命令安装它:pip install pymongo然后,使用以下代码连接到数据库:
from pymongo import MongoClient client = MongoClient("mongodb://your_user:your_password@your_host:your_port/your_database") db = client.your_database # Your code to interact with the database goes here
请根据您要连接的数据库类型选择合适的方法,并确保已安装相应的库。
以上就是关于“Ubuntu下Python如何连接数据库”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm