在Ubuntu上配置Python数据库连接,首先需要确保已经安装了Python和相应的数据库驱动。以下是一些常见数据库的连接配置方法:
首先,安装MySQL数据库和Python的MySQL驱动:
sudo apt-get install mysql-server
pip install mysql-connector-python
然后,在Python代码中使用mysql.connector模块连接数据库:
import mysql.connector
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = cnx.cursor()
# 执行SQL查询和其他操作
cursor.close()
cnx.close()
首先,安装PostgreSQL数据库和Python的psycopg2驱动:
sudo apt-get install postgresql postgresql-contrib
pip install psycopg2
然后,在Python代码中使用psycopg2模块连接数据库:
import psycopg2
conn = psycopg2.connect(
dbname="your_database",
user="your_username",
password="your_password",
host="localhost"
)
cursor = conn.cursor()
# 执行SQL查询和其他操作
cursor.close()
conn.close()
SQLite是一个轻量级的数据库,不需要单独安装。Python内置了对SQLite的支持,可以直接使用sqlite3模块连接数据库:
import sqlite3
conn = sqlite3.connect("your_database.db")
cursor = conn.cursor()
# 执行SQL查询和其他操作
cursor.close()
conn.close()
注意:在实际应用中,建议使用环境变量或配置文件来存储数据库连接信息,以保护敏感数据。