linux安装mysql,python连接
时间: 2024-08-16 19:00:23 浏览: 40
在Linux上安装MySQL,通常分为几个步骤:
1. **下载并安装**:
- 打开终端,更新软件包列表:`sudo apt update`
- 安装MySQL Server:如果是Debian或Ubuntu系统,可以使用`sudo apt install mysql-server`
2. **启动服务**:
- 完成安装后,运行`sudo systemctl start mysql` 启动服务,然后设置自动启动:`sudo systemctl enable mysql`
3. **初始化数据库**:
首次运行可能会提示你创建root用户密码。
4. **安全管理**:
推荐配置防火墙允许特定IP访问,并创建安全的MySQL用户账户。
Python连接MySQL通常通过Python的数据库适配器如`pymysql`或`mysql-connector-python`来进行。以下是基本的安装和连接步骤:
1. 安装库:
对于`pip`管理的库,你可以使用命令 `pip install pymysql` 或者 `pip install mysql-connector-python`。
2. 连接示例(使用pymysql):
```python
import pymysql
# 创建连接
conn = pymysql.connect(host='localhost', user='your_username', password='your_password',
db='your_database_name')
# 创建游标
cursor = conn.cursor()
# 执行SQL查询
cursor.execute("SELECT * FROM your_table")
# 获取结果
rows = cursor.fetchall()
for row in rows:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
```
记得将上述代码中的`your_username`、`your_password`和`your_database_name`替换为你实际的MySQL账号信息。
阅读全文
相关推荐















