pythono连接mysql数据库
时间: 2024-10-03 18:03:06 浏览: 27
Python连接MySQL数据库通常使用的是`pymysql`库或者是更推荐的`mysql-connector-python`库,这两个库都提供了一种简单的方式来操作MySQL数据库。以下是使用`pymysql`的一个基本示例:
```python
import pymysql
# 连接数据库
def connect_to_mysql():
host = 'localhost'
user = 'your_username'
password = 'your_password'
db = 'your_database'
# 创建连接
connection = pymysql.connect(host=host,
user=user,
password=password,
database=db)
return connection
# 使用连接执行SQL查询
def execute_query(connection):
cursor = connection.cursor()
sql = "SELECT * FROM your_table"
cursor.execute(sql)
# 获取结果
results = cursor.fetchall()
for row in results:
print(row)
# 示例
connection = connect_to_mysql()
execute_query(connection)
connection.close() # 关闭连接
阅读全文