ubuntu

Ubuntu上Python数据库连接怎么配置

小樊
40
2025-03-16 14:31:42
栏目: 编程语言
亿速云数据库,弹性扩容,低至0.3元/天! 查看>>

在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()

总结

  1. 确定数据库类型:根据需求选择合适的数据库。
  2. 安装数据库服务器:使用apt包管理器安装相应的数据库服务器。
  3. 创建数据库和用户:配置数据库和用户权限。
  4. 安装Python驱动:使用pip安装相应的Python数据库驱动。
  5. 编写连接代码:根据所选数据库类型编写连接和操作数据库的Python代码。

通过以上步骤,你可以在Ubuntu上成功配置Python数据库连接。

亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>

相关推荐:如何在Ubuntu上配置Python数据库连接

0
看了该问题的人还看了