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

30次阅读
没有评论

共计 1040 个字符,预计需要花费 3 分钟才能阅读完成。

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 查询,最后关闭连接。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计1040字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)