在Ubuntu上使用Python连接数据库,通常需要使用相应的数据库驱动程序。以下是一些常见数据库的连接操作:
首先,确保已经安装了MySQL数据库和Python的MySQL驱动程序mysql-connector-python
。可以使用以下命令安装:
sudo apt-get install mysql-server
pip install mysql-connector-python
然后,使用以下代码连接到MySQL数据库:
import mysql.connector
# 创建连接
cnx = mysql.connector.connect(
host="your_host",
user="your_user",
password="your_password",
database="your_database"
)
# 创建游标
cursor = cnx.cursor()
# 执行SQL查询
query = "SELECT * FROM your_table"
cursor.execute(query)
# 获取查询结果
for row in cursor.fetchall():
print(row)
# 关闭游标和连接
cursor.close()
cnx.close()
首先,确保已经安装了PostgreSQL数据库和Python的PostgreSQL驱动程序psycopg2
。可以使用以下命令安装:
sudo apt-get install postgresql postgresql-contrib
pip install psycopg2
然后,使用以下代码连接到PostgreSQL数据库:
import psycopg2
# 创建连接
conn = psycopg2.connect(
dbname="your_database",
user="your_user",
password="your_password",
host="your_host",
port="your_port"
)
# 创建游标
cur = conn.cursor()
# 执行SQL查询
query = "SELECT * FROM your_table"
cur.execute(query)
# 获取查询结果
rows = cur.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cur.close()
conn.close()
对于SQLite数据库,Python内置了sqlite3
模块,无需额外安装。使用以下代码连接到SQLite数据库:
import sqlite3
# 创建连接
conn = sqlite3.connect('your_database.db')
# 创建游标
cursor = conn.cursor()
# 执行SQL查询
query = "SELECT * FROM your_table"
cursor.execute(query)
# 获取查询结果
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
根据需要选择合适的数据库驱动程序,并按照相应的步骤进行操作。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: Ubuntu中如何自动化日常任务