python连接数据库的代码
时间: 2024-06-23 15:01:01 浏览: 18
Python连接数据库通常使用一些流行的库,比如SQLite、MySQL、PostgreSQL等。这里以使用Python的sqlite3库和pymysql库作为例子:
1. 连接SQLite数据库(无需安装额外库,因为SQLite是Python的标准库):
```python
import sqlite3
# 连接到SQLite数据库
conn = sqlite3.connect('example.db') # 数据库文件名
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM table_name")
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭连接
conn.close()
```
2. 连接MySQL数据库(需要安装pymysql库,可以通过pip install pymysql进行安装):
```python
import pymysql
# 连接到MySQL服务器
db = pymysql.connect(host='localhost', user='username', password='password', db='database_name')
cursor = db.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM table_name")
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭连接
db.close()
```
3. 连接PostgreSQL数据库(需要安装psycopg2库,可以通过pip install psycopg2进行安装):
```python
import psycopg2
# 连接到PostgreSQL服务器
conn = psycopg2.connect(database="database_name", user="username", password="password", host="localhost", port=5432)
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM table_name")
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭连接
conn.close()
```
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)