Python连接数据库的代码
网站编辑2023-09-02 15:27:42458
在Python中,连接数据库是非常常见的操作。无论是用于存储数据、读取数据还是进行数据分析,连接数据库都是必不可少的一步。本文将介绍使用Python连接数据库的常用代码。
1. 使用MySQL数据库
```python import mysql.connector
mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="yourdatabase" )
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM yourtable")
result = mycursor.fetchall()
for row in result: print(row) ```
2. 使用SQLite数据库
```python import sqlite3
conn = sqlite3.connect('yourdatabase.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM yourtable")
result = cursor.fetchall()
for row in result: print(row) ```
3. 使用MongoDB数据库
```python from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['yourdatabase']
collection = db['yourcollection']
result = collection.find()
for doc in result: print(doc) ```
以上是使用Python连接MySQL、SQLite和MongoDB数据库的代码示例。根据具体的数据库类型和连接参数,可以进行相应的修改和调整。连接数据库后,可以执行SQL语句或者进行数据查询操作,获取结果并进行进一步的处理和分析。







