在Ubuntu上使用Python连接数据库,通常需要安装相应的数据库驱动程序。以下是一些常见数据库的连接方法:
首先,确保你已经安装了MySQL服务器。然后,使用pip安装mysql-connector-python
或PyMySQL
库。
pip install mysql-connector-python
或者
pip install PyMySQL
mysql-connector-python
连接MySQLimport mysql.connector
# 连接到MySQL数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建一个游标对象
mycursor = mydb.cursor()
# 执行SQL查询
mycursor.execute("SELECT * FROM yourtable")
# 获取查询结果
myresult = mycursor.fetchall()
for x in myresult:
print(x)
PyMySQL
连接MySQLimport pymysql
# 连接到MySQL数据库
conn = pymysql.connect(
host='localhost',
user='yourusername',
password='yourpassword',
db='yourdatabase'
)
# 创建一个游标对象
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM yourtable")
# 获取查询结果
results = cursor.fetchall()
for row in results:
print(row)
首先,确保你已经安装了PostgreSQL服务器。然后,使用pip安装psycopg2
库。
pip install psycopg2
psycopg2
连接PostgreSQLimport psycopg2
# 连接到PostgreSQL数据库
conn = psycopg2.connect(
dbname="yourdatabase",
user="yourusername",
password="yourpassword",
host="localhost"
)
# 创建一个游标对象
cur = conn.cursor()
# 执行SQL查询
cur.execute("SELECT * FROM yourtable")
# 获取查询结果
rows = cur.fetchall()
for row in rows:
print(row)
SQLite是一个嵌入式数据库,不需要单独的服务器进程。使用Python内置的sqlite3
模块即可连接。
import sqlite3
# 连接到SQLite数据库
conn = sqlite3.connect('yourdatabase.db')
# 创建一个游标对象
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM yourtable")
# 获取查询结果
rows = cursor.fetchall()
for row in rows:
print(row)
通过以上步骤,你可以在Ubuntu上使用Python连接并操作数据库。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: 如何通过Ubuntu lsof命令查找进程