阅读量:1
以下是在Ubuntu上使用Python连接不同数据库的教程:
连接MySQL数据库
- 安装驱动:
pip install mysql-connector-python。 - 安装数据库服务器:
sudo apt update,sudo apt install mysql-server,然后运行sudo mysql_secure_installation进行安全设置。 - 编写代码:
import mysql.connector
try:
connection = mysql.connector.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
if connection.is_connected():
cursor = connection.cursor()
cursor.execute("SELECT * FROM your_table")
result = cursor.fetchall()
for row in result:
print(row)
finally:
if connection.is_connected():
cursor.close()
connection.close()
连接PostgreSQL数据库
- 安装驱动:
pip install psycopg2。 - 安装数据库服务器:
sudo apt update,sudo apt install postgresql postgresql-contrib。 - 编写代码:
import psycopg2
try:
connection = psycopg2.connect(
dbname='your_database',
user='your_username',
password='your_password',
host='localhost'
)
cursor = connection.cursor()
cursor.execute("SELECT * FROM your_table")
rows = cursor.fetchall()
for row in rows:
print(row)
finally:
if connection:
cursor.close()
connection.close()
连接SQLite数据库
- 安装驱动:Python标准库已包含
sqlite3模块,无需额外安装。 - 编写代码:
import sqlite3
connection = sqlite3.connect('your_database.db')
cursor = connection.cursor()
cursor.execute("SELECT * FROM your_table")
rows = cursor.fetchall()
for row in rows:
print(row)
cursor.close()
connection.close()
连接MongoDB数据库
- 安装驱动:
pip install pymongo。 - 编写代码:
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database']
collection = db['your_collection']
documents = collection.find()
for document in documents:
print(document)
client.close
以上就是关于“Ubuntu Python数据库连接教程”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm