温馨提示×

Ubuntu Python数据库连接怎么操作

小樊
58
2025-04-13 17:11:41
栏目: 编程语言

在Ubuntu上使用Python连接数据库,通常需要使用相应的数据库驱动程序。以下是一些常见数据库的连接操作:

  1. 连接MySQL数据库

首先,确保已经安装了MySQL数据库和Python的MySQL驱动程序mysql-connector-python。可以使用以下命令安装:

sudo apt-get install mysql-server pip install mysql-connector-python 

然后,使用以下代码连接到MySQL数据库:

import mysql.connector # 创建连接 cnx = mysql.connector.connect( host="your_host", user="your_user", password="your_password", database="your_database" ) # 创建游标 cursor = cnx.cursor() # 执行SQL查询 query = "SELECT * FROM your_table" cursor.execute(query) # 获取查询结果 for row in cursor.fetchall(): print(row) # 关闭游标和连接 cursor.close() cnx.close() 
  1. 连接PostgreSQL数据库

首先,确保已经安装了PostgreSQL数据库和Python的PostgreSQL驱动程序psycopg2。可以使用以下命令安装:

sudo apt-get install postgresql postgresql-contrib pip install psycopg2 

然后,使用以下代码连接到PostgreSQL数据库:

import psycopg2 # 创建连接 conn = psycopg2.connect( dbname="your_database", user="your_user", password="your_password", host="your_host", port="your_port" ) # 创建游标 cur = conn.cursor() # 执行SQL查询 query = "SELECT * FROM your_table" cur.execute(query) # 获取查询结果 rows = cur.fetchall() for row in rows: print(row) # 关闭游标和连接 cur.close() conn.close() 
  1. 连接SQLite数据库

对于SQLite数据库,Python内置了sqlite3模块,无需额外安装。使用以下代码连接到SQLite数据库:

import sqlite3 # 创建连接 conn = sqlite3.connect('your_database.db') # 创建游标 cursor = conn.cursor() # 执行SQL查询 query = "SELECT * FROM your_table" cursor.execute(query) # 获取查询结果 rows = cursor.fetchall() for row in rows: print(row) # 关闭游标和连接 cursor.close() conn.close() 

根据需要选择合适的数据库驱动程序,并按照相应的步骤进行操作。

0