阅读量:0
在Debian系统下,Python可以通过多种方式连接到数据库。以下是一些常见的数据库及其对应的Python连接方法:
- MySQL/MariaDB:
使用mysql-connector-python或PyMySQL库来连接MySQL或MariaDB数据库。
安装库:
pip install mysql-connector-python
# 或者
pip install pymysql
示例代码 (使用mysql-connector-python):
import mysql.connector
cnx = mysql.connector.connect(user='username', password='password', host='localhost', database='mydb')
cursor = cnx.cursor()
query = "SELECT * FROM mytable"
cursor.execute(query)
for row in cursor:
print(row)
cursor.close()
cnx.close()
- PostgreSQL:
使用psycopg2库来连接PostgreSQL数据库。
安装库:
pip install psycopg2
# 或者
pip install psycopg2-binary
示例代码:
import psycopg2
conn = psycopg2.connect(user='username', password='password', host='localhost', dbname='mydb')
cur = conn.cursor()
cur.execute("SELECT * FROM mytable")
rows = cur.fetchall()
for row in rows:
print(row)
cur.close()
conn.close()
- SQLite:
Python内置了对SQLite的支持,无需安装额外的库。
示例代码:
import sqlite3
conn = sqlite3.connect('mydb.sqlite3')
cursor = conn.cursor()
cursor.execute("SELECT * FROM mytable")
rows = cursor.fetchall()
for row in rows:
print(row)
cursor.close()
conn.close()
- MongoDB:
使用pymongo库来连接MongoDB数据库。
安装库:
pip install pymongo
示例代码:
from pymongo import MongoClient
client = MongoClient('mongodb://username:password@localhost:27017/mydb')
db = client['mydb']
collection = db['mytable']
documents = collection.find()
for doc in documents:
print(doc)
请根据您使用的数据库类型选择合适的库,并按照示例代码进行操作。注意替换示例代码中的username、password、host、database和mytable等参数为您自己的数据库信息。
以上就是关于“Debian下Python与数据库如何连接”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm