温馨提示×

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

小亿
85
2023-12-04 12:14:46
栏目: 编程语言
亿速云云数据库,读写分离,安全稳定,弹性扩容,低至0.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查询,最后关闭连接。

亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>

推荐阅读:jdbc连接数据库的方法是什么

0