python数据库接口
时间: 2023-07-25 16:10:17 浏览: 51
Python提供了多种数据库接口,最常用的是Python DB API。Python DB API是Python数据库应用程序接口的标准化模块,它定义了一组Python对象和方法,用于连接和操作数据库。
Python DB API支持多种数据库,包括MySQL、Oracle、PostgreSQL等。你可以使用Python DB API连接数据库、执行SQL查询、获取结果等。
以下是使用Python DB API连接MySQL的示例代码:
```python
import mysql.connector
# 连接数据库
cnx = mysql.connector.connect(user='username', password='password',
host='localhost',
database='database_name')
# 执行SQL查询
cursor = cnx.cursor()
query = ("SELECT id, name, age FROM users "
"WHERE age = %s")
cursor.execute(query, (25,))
# 获取查询结果
for (id, name, age) in cursor:
print("{} - {}: {}".format(id, name, age))
# 关闭连接
cursor.close()
cnx.close()
```
在上面的示例代码中,我们使用`mysql.connector`模块连接MySQL数据库,并执行一个查询,最后获取查询结果。你可以根据需要修改连接字符串、SQL查询语句和查询参数。