阅读量:122
在Ubuntu上配置Python数据库连接,首先需要确定你想要连接的数据库类型(例如MySQL、PostgreSQL、SQLite等)。以下是针对几种常见数据库的配置步骤:
1. MySQL安装MySQL服务器
sudo apt update
sudo apt install mysql-server
安装Python的MySQL驱动
pip install mysql-connector-python
示例代码
import mysql.connector
# 连接到数据库
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)
2. PostgreSQL安装PostgreSQL服务器
sudo apt update
sudo apt install postgresql postgresql-contrib
创建数据库和用户
sudo -u postgres psql
在psql shell中:
CREATE DATABASE yourdatabase;
CREATE USER yourusername WITH ENCRYPTED PASSWORD 'yourpassword';
GRANT ALL PRIVILEGES ON DATABASE yourdatabase TO yourusername;
\q
安装Python的PostgreSQL驱动
pip install psycopg2-binary
示例代码
import psycopg2
# 连接到数据库
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)
3. SQLite
SQLite是一个嵌入式数据库,不需要单独安装服务器。
安装Python的SQLite驱动
pip install pysqlite3
示例代码
import sqlite3
# 连接到数据库
conn = sqlite3.connect('yourdatabase.db')
# 创建游标对象
cursor = conn.cursor()
# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS yourtable (id INTEGER PRIMARY KEY, name TEXT)''')
# 插入数据
cursor.execute("INSERT INTO yourtable (name) VALUES ('Alice')")
# 提交事务
conn.commit()
# 查询数据
cursor.execute("SELECT * FROM yourtable")
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭连接
conn.close()
总结确定数据库类型:根据需求选择合适的数据库。安装数据库服务器:使用apt包管理器安装相应的数据库服务器。创建数据库和用户:配置数据库和用户权限。安装Python驱动:使用pip安装相应的Python数据库驱动。编写连接代码:根据所选数据库类型编写连接和操作数据库的Python代码。
通过以上步骤,你可以在Ubuntu上成功配置Python数据库连接。