温馨提示×

Python连接数据库的方法是什么

小亿
80
2023-12-04 12:14:46
栏目: 编程语言

Python连接数据库的方法有多种,可以使用标准库中的sqlite3模块连接SQLite数据库,也可以使用第三方库如MySQLdb、psycopg2等连接MySQL或PostgreSQL数据库。以下是连接MySQL、PostgreSQL和SQLite数据库的示例代码:

  1. 连接MySQL数据库:
import MySQLdb

# 连接数据库
conn = MySQLdb.connect(host='localhost', user='username', passwd='password', db='database_name')

# 获取游标
cursor = conn.cursor()

# 执行SQL查询
cursor.execute('SELECT * FROM table_name')

# 获取查询结果
results = cursor.fetchall()

# 关闭连接
cursor.close()
conn.close()
  1. 连接PostgreSQL数据库:
import psycopg2

# 连接数据库
conn = psycopg2.connect(host='localhost', user='username', password='password', dbname='database_name')

# 获取游标
cursor = conn.cursor()

# 执行SQL查询
cursor.execute('SELECT * FROM table_name')

# 获取查询结果
results = cursor.fetchall()

# 关闭连接
cursor.close()
conn.close()
  1. 连接SQLite数据库:
import sqlite3

# 连接数据库
conn = sqlite3.connect('database.db')

# 获取游标
cursor = conn.cursor()

# 执行SQL查询
cursor.execute('SELECT * FROM table_name')

# 获取查询结果
results = cursor.fetchall()

# 关闭连接
cursor.close()
conn.close()

这些示例代码中,首先使用相应的库连接数据库,然后获取游标进行SQL查询,最后关闭连接。

0