温馨提示×

Debian Python数据库连接方法有哪些

小樊
54
2025-02-20 06:36:58
栏目: 编程语言

在Debian系统上使用Python连接数据库,通常需要安装相应的数据库连接库。以下是一些常见的数据库及其对应的Python连接库和方法:

MySQL/MariaDB

  • 安装库mysql-connector-pythonpymysql
  • 连接方法
    1. 导入库:import mysql.connectorimport pymysql
    2. 创建连接:connection = mysql.connector.connect(host='host', user='user', password='password', database='database')connection = pymysql.connect(host='host', user='user', password='password', db='database')
    3. 创建游标:cursor = connection.cursor()
    4. 执行查询:cursor.execute('SQL_QUERY')
    5. 获取结果:results = cursor.fetchall()results = cursor.fetchone()
    6. 关闭连接:cursor.close()connection.close()

PostgreSQL

  • 安装库psycopg2
  • 连接方法
    1. 导入库:import psycopg2
    2. 创建连接:connection = psycopg2.connect(host='host', user='user', password='password', dbname='database')
    3. 创建游标:cursor = connection.cursor()
    4. 执行查询:cursor.execute('SQL_QUERY')
    5. 获取结果:results = cursor.fetchall()results = cursor.fetchone()
    6. 关闭连接:cursor.close()connection.close()

SQLite

  • 安装库sqlite3(Python标准库的一部分,无需额外安装)
  • 连接方法
    1. 导入库:import sqlite3
    2. 创建连接:connection = sqlite3.connect('database.db')
    3. 创建游标:cursor = connection.cursor()
    4. 执行查询:cursor.execute('SQL_QUERY')
    5. 获取结果:results = cursor.fetchall()results = cursor.fetchone()
    6. 关闭连接:cursor.close()connection.close()

Teradata

  • 安装库teradatasql
  • 连接方法
    1. 导入库:import teradatasql
    2. 配置连接参数:定义主机名、端口号、用户名和密码。
    3. 建立连接:connection = teradatasql.connect(host=host, user=user, password=password)
    4. 执行SQL查询:cursor = connection.cursor()cursor.execute('SQL_QUERY')
    5. 获取结果:rows = cursor.fetchall(),遍历结果并打印。
    6. 关闭连接:cursor.close()connection.close()

以上是在Debian系统上使用Python连接不同类型数据库的一般方法。具体安装库的命令可以通过pip install package_name来执行,其中package_name是对应数据库的Python连接库名称。

0