在CentOS上使用Python连接数据库,通常会使用一些流行的数据库驱动程序。以下是一些常见的数据库及其对应的Python连接方法:
MySQL/MariaDB
对于MySQL或MariaDB数据库,可以使用mysql-connector-python
或PyMySQL
库来连接。
安装mysql-connector-python
:
pip install mysql-connector-python
使用mysql-connector-python
连接数据库的示例代码:
import mysql.connector
cnx = mysql.connector.connect(user='username', password='password',
host='127.0.0.1',
database='mydatabase')
cursor = cnx.cursor()
query = ("SELECT * FROM mytable")
cursor.execute(query)
for row in cursor:
print(row)
cursor.close()
cnx.close()
安装PyMySQL
:
pip install PyMySQL
使用PyMySQL
连接数据库的示例代码:
import pymysql
cnx = pymysql.connect(user='username', password='password',
host='127.0.0.1',
database='mydatabase')
cursor = cnx.cursor()
query = ("SELECT * FROM mytable")
cursor.execute(query)
results = cursor.fetchall()
for row in results:
print(row)
cursor.close()
cnx.close()
PostgreSQL
对于PostgreSQL数据库,可以使用psycopg2
库来连接。
安装psycopg2
:
pip install psycopg2-binary
使用psycopg2
连接数据库的示例代码:
import psycopg2
conn = psycopg2.connect(dbname="mydatabase", user="username",
password="password", host="127.0.0.1")
cur = conn.cursor()
cur.execute("SELECT * FROM mytable;")
rows = cur.fetchall()
for row in rows:
print(row)
cur.close()
conn.close()
SQLite
对于SQLite数据库,可以使用Python内置的sqlite3
模块来连接。
使用sqlite3
连接数据库的示例代码:
import sqlite3
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()
cursor.execute("SELECT sqlite_version();")
data = cursor.fetchone()
print("SQLite version:", data)
conn.close()
在连接到数据库之前,请确保已经安装了相应的数据库服务器,并且数据库服务正在运行。此外,还需要确保数据库用户具有相应的权限,并且数据库名称、用户名和密码都是正确的。