p ython怎么和mysql连接
时间: 2024-10-11 21:05:15 浏览: 75
Python连接MySQL数据库通常通过使用第三方库如`pymysql`、`mysql-connector-python`或`sqlite3`(如果目标是SQLite而不是MySQL)。以下是使用`pymysql`的一个简单示例:
```python
import pymysql
# 连接到MySQL服务器
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
# 执行查询
def execute_query(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
result = cursor.fetchall() # 获取所有结果
print(result)
except Exception as e:
print(f"Error executing query: {e}")
finally:
cursor.close()
connection.close()
# 使用连接
connection = connect_to_mysql()
query = "SELECT * FROM your_table"
execute_query(connection, query)
```
阅读全文