在Debian系统上使用Python连接数据库,通常需要安装相应的数据库连接库。以下是一些常见的数据库及其对应的Python连接库和方法:
MySQL/MariaDB
- 安装库:
mysql-connector-python
或pymysql
- 连接方法:
- 导入库:
import mysql.connector
或import pymysql
- 创建连接:
connection = mysql.connector.connect(host='host', user='user', password='password', database='database')
或connection = pymysql.connect(host='host', user='user', password='password', db='database')
- 创建游标:
cursor = connection.cursor()
- 执行查询:
cursor.execute('SQL_QUERY')
- 获取结果:
results = cursor.fetchall()
或results = cursor.fetchone()
- 关闭连接:
cursor.close()
和connection.close()
- 导入库:
PostgreSQL
- 安装库:
psycopg2
- 连接方法:
- 导入库:
import psycopg2
- 创建连接:
connection = psycopg2.connect(host='host', user='user', password='password', dbname='database')
- 创建游标:
cursor = connection.cursor()
- 执行查询:
cursor.execute('SQL_QUERY')
- 获取结果:
results = cursor.fetchall()
或results = cursor.fetchone()
- 关闭连接:
cursor.close()
和connection.close()
- 导入库:
SQLite
- 安装库:
sqlite3
(Python标准库的一部分,无需额外安装) - 连接方法:
- 导入库:
import sqlite3
- 创建连接:
connection = sqlite3.connect('database.db')
- 创建游标:
cursor = connection.cursor()
- 执行查询:
cursor.execute('SQL_QUERY')
- 获取结果:
results = cursor.fetchall()
或results = cursor.fetchone()
- 关闭连接:
cursor.close()
和connection.close()
- 导入库:
Teradata
- 安装库:
teradatasql
- 连接方法:
- 导入库:
import teradatasql
- 配置连接参数:定义主机名、端口号、用户名和密码。
- 建立连接:
connection = teradatasql.connect(host=host, user=user, password=password)
- 执行SQL查询:
cursor = connection.cursor()
,cursor.execute('SQL_QUERY')
- 获取结果:
rows = cursor.fetchall()
,遍历结果并打印。 - 关闭连接:
cursor.close()
和connection.close()
- 导入库:
以上是在Debian系统上使用Python连接不同类型数据库的一般方法。具体安装库的命令可以通过pip install package_name
来执行,其中package_name
是对应数据库的Python连接库名称。