在Ubuntu上使用Python连接数据库,通常需要以下几个步骤:
sudo apt update
sudo apt install mysql-server
对于PostgreSQL,可以使用:
sudo apt update
sudo apt install postgresql postgresql-contrib
mysql-connector-python
或pymysql
。对于PostgreSQL,可以使用psycopg2
。使用pip安装这些库的命令如下:
# 对于MySQL
pip install mysql-connector-python
# 或者
pip install pymysql
# 对于PostgreSQL
pip install psycopg2
如果你使用的是Python 3,可能需要使用pip3
来安装。
mysql-connector-python
连接到MySQL数据库:import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(
host='localhost',
database='your_database',
user='your_username',
password='your_password'
)
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Database version ", db_Info)
cursor = connection.cursor()
cursor.execute("SELECT DATABASE();")
record = cursor.fetchone()
print("You're connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
请确保将your_database
、your_username
和your_password
替换为你的实际数据库名称、用户名和密码。
对于PostgreSQL,连接代码会略有不同:
import psycopg2
try:
connection = psycopg2.connect(
dbname='your_database',
user='your_username',
password='your_password',
host='localhost'
)
print("Connected to PostgreSQL database")
except psycopg2.Error as e:
print("Unable to connect to the database")
print(e)
finally:
if connection:
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
同样地,替换your_database
、your_username
和your_password
为你的实际数据库信息。
python your_script.py
# 或者如果你使用的是Python 3
python3 your_script.py
确保你的数据库服务正在运行,并且你的防火墙设置允许数据库连接。如果你遇到任何连接问题,请检查数据库服务的状态、用户权限和网络配置。