pyhtonl连接数据库
时间: 2023-09-20 13:13:37 浏览: 29
在Python中连接数据库的方法有很多,这里我给你介绍两种比较常用的方法:
方法一:使用Python DB API进行连接
如果你已经安装了数据库的Python DB API驱动程序,比如说MySQLdb,那么你可以使用以下代码连接数据库:
```python
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect(host="localhost", user="testuser", passwd="test123", db="testdb")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT * FROM employee")
# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
# 打印数据
print(data)
# 关闭数据库连接
db.close()
```
方法二:使用SQLAlchemy进行连接
如果你使用的是SQLAlchemy这个Python SQL工具包,那么你可以使用以下代码连接数据库:
```python
from sqlalchemy import create_engine
# 创建数据库连接
engine = create_engine('mysql://testuser:test123@localhost/testdb')
# 执行SQL查询
result = engine.execute('SELECT * FROM employee')
# 打印数据
for row in result:
print(row)
# 关闭数据库连接
engine.dispose()
```
以上两种方法都是比较常用的数据库连接方法,具体使用哪种方法,取决于你使用的数据库类型和个人喜好。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)